package com.wing.cabinet.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.bill.service.BillOrdInformationDetailService;
import com.wing.bill.service.BillOrdInformationService;
import com.wing.cabinet.dao.*;
import com.wing.cabinet.model.entity.*;
import com.wing.cabinet.model.request.*;
import com.wing.cabinet.model.response.AuthorityMemberVO;
import com.wing.cabinet.model.response.CellInventoryInoutDetailVO;
import com.wing.cabinet.model.response.CellInventoryInoutVO;
import com.wing.cabinet.model.response.StorageInventoryInoutVO;
import com.wing.cabinet.utils.MailSenderConfig;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.Result;
import com.wing.config.BaseDataInit;
import com.wing.constant.CabConstants;
import com.wing.order.dao.DynamicDao;
import com.wing.order.model.entity.*;
import com.wing.order.model.request.OrderReceiveLoadDetailForm;
import com.wing.order.model.request.OrderReceiveLoadForm;
import com.wing.order.model.response.OrderDeliveryDetailVO;
import com.wing.order.model.response.OrderReceiveDetailVO;
import com.wing.order.service.*;
import com.wing.product.model.entity.ProductDetail;
import com.wing.product.model.entity.ProductPack;
import com.wing.product.model.response.ProductDetailVO;
import com.wing.product.model.response.ProductPackVO;
import com.wing.product.service.ProductDetailService;
import com.wing.product.service.ProductPackService;
import com.wing.productself.service.ProductDetailSelfService;
import com.wing.setting.model.entity.SystemRuleInfo;
import com.wing.setting.service.SystemRuleInfoService;
import com.wing.user.feign.UserClient;
import com.wing.user.model.response.UserVO;
import com.wing.util.PulsarCommons;
import com.wing.util.PulsarUtils;
import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import javax.annotation.Resource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

/**
 * 售刀柜上货(上货主表无展示)/领取明细-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class CellInventoryInoutDetailServiceImpl extends ServiceImpl<CellInventoryInoutDetailDao, CellInventoryInoutDetail> implements CellInventoryInoutDetailService {

    @Autowired
    private DynamicService dynamicService;

    @Autowired
    private CellInventoryInoutService inventoryInoutService;

    @Autowired
    private CellInventoryProductService cellInventoryProductService;

    @Autowired
    private CellInventorySpaceService cellInventorySpaceService;

    @Autowired
    private UseInventoryInoutDetailService useInventoryInoutDetailService;

    @Autowired
    private CellSingleInventoryProductService cellSingleInventoryProductService;

    @Autowired
    private CabinetCargoLaneService laneService;

    @Autowired
    private OrderDeliveryLoadService deliveryLoadService;

    @Autowired
    private OrderDeliveryDetailService deliveryDetailService;

//    @Autowired
//    private OrderReceiveLoadService receiveLoadService;

    @Autowired
    private OrderReceiveDetailService receiveDetailService;

    @Autowired
    private OrderReceiveService receiveService;

    @Autowired
    private SkuDeviceService skuDeviceService;

    @Autowired
    private OrderReceiveLoadService orderReceiveLoadService;

    @Value("${pulsar.client.topicUrl}")
    private String topicUrl;
    @Autowired
    private EnterpricceIdService enterpricceIdService;

    @Autowired
    private CellInventoryOutSeqService cellInventoryOutSeqService;

    @Autowired
    private OrderDeviceService orderDeviceService;

    @Autowired
    private CellInventoryOutAmountService cellInventoryOutAmountService;

    @Autowired
    private SystemRuleInfoService systemRuleInfoService;

    @Autowired
    private OrderReceiveLoadDetailService orderReceiveLoadDetailService;

    @Autowired
    private CabinetService cabinetService;

    @Autowired
    private AuthorityManageService authorityManageService;

    @Autowired
    private AuthorityMemberService authorityMemberService;

    @Autowired
    private ProductDetailSelfService productDetailSelfService;

    @Autowired
    private ReceiveRecordService receiveRecordService;

    @Autowired
    private UserClient userClient;

    @Autowired
    private StoresRequisitionService storesRequisitionService;

    @Autowired
    private CountQuotaService countQuotaService;

    @Autowired
    private CabInventoryProductService cabInventoryProductService;

    @Autowired
    private ProductDetailService productDetailService;

    @Autowired
    private StorageInventoryInoutDetailService storageInventoryInoutDetailService;

    @Autowired
    private DynamicDao dynamicDao;
    @Autowired
    private CellInventoryInoutDetailDao cellInventoryInoutDetailDao;
    @Autowired
    private BillOrdInformationService billOrdInformationService;
    @Autowired
    private BillOrdInformationDetailService billOrdInformationDetailService;

//    @Autowired
//    private OrderReceiveDetailService orderReceiveDetailService;

    @Autowired
    private UseInventoryUserService useInventoryUserService;
    @Autowired
    private AuthorityMaterielService authorityMaterielService;

    @Autowired
    private ProductPackService productPackService;

    private ExecutorService executorService= Executors.newFixedThreadPool(10);

    @Autowired
    private CabAlarmSettingsService cabAlarmSettingsService;

    @Resource
    private JavaMailSender javaMailSender;
    @Autowired
    private MailInfo mailInfo;
    @Autowired
    private CutterLifeCycleService cutterLifeCycleService;
    @Autowired
    private UseInventoryUserKnifeService useInventoryUserKnifeService;

    @Autowired
    private CellInventoryInoutService cellInventoryInoutService;
    @Autowired
    private StorageInventoryInoutService storageInventoryInoutService;

    @Autowired
    MailSenderConfig senderConfig;

    @Autowired
    private AuthorityMemberDao authorityMemberDao;

    @Autowired
    private AboveTheQuotaApplyProductDao aboveTheQuotaApplyProductDao;
    @Autowired
    private AboveTheQuotaApplyDao aboveTheQuotaApplyDao;

    @Override
    public int add(CellInventoryInoutDetailForm cellInventoryInoutDetailForm) {

        //校验

        CellInventoryInoutDetail cellInventoryInoutDetail =new CellInventoryInoutDetail();
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(CellInventoryInoutDetail.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(cellInventoryInoutDetailForm, cellInventoryInoutDetail, copyOptions);

        return baseMapper.insert(cellInventoryInoutDetail);
    }

    @Override
    public List<CellInventoryInoutDetailVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<CellInventoryInoutDetailVO> pageList4app(Page page, Map<String, Object> params) {
        List<CellInventoryInoutDetailVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public CellInventoryInoutDetailVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }
    @Override
    public CellInventoryInoutDetailVO getCellById(Long inoutId){
        return baseMapper.getByInoutId(inoutId);
    }

    BigDecimal getTotal(List<CellInventoryInoutDetailForm> list){
        BigDecimal sum=BigDecimal.valueOf(0);
        for (CellInventoryInoutDetailForm cellInventoryInoutDetailForm:list){
            List<ProductDetail> productDetails=productDetailService.list(new QueryWrapper<ProductDetail>().eq("sku_code",cellInventoryInoutDetailForm.getSkuCode()));
            if (productDetails.size()>0&&productDetails.get(0).getMarketPrice()!=null){
                cellInventoryInoutDetailForm.setPrice(productDetails.get(0).getMarketPrice());
                BigDecimal total=BigDecimal.valueOf(cellInventoryInoutDetailForm.getQuantity()).multiply(productDetails.get(0).getMarketPrice());
                cellInventoryInoutDetailForm.setTotal(total);
                sum=sum.add(total);
            }
        }
        return sum;
    }

    @Override
    @Transactional
    public CellInventoryInout inventoryOut(CellInventoryInoutForm cellInventoryInoutForm) {
        CellInventoryInout cellInventoryInout=new CellInventoryInout();
        cellInventoryInout.setLabelCodeList(new ArrayList<>());
        CellInventoryInoutForm cellInventoryInoutForm1=getCellInventoryInoutForm(cellInventoryInoutForm);
        if (cellInventoryInoutForm1.getDetailList().size()>0){
            cellInventoryInout=this.inventoryOut(cellInventoryInoutForm1.getDetailList(),cellInventoryInoutForm1.getDeviceCode(),CellInventoryInout.BusinessType.cellCabOut, UseInventoryInout.BusinessType.cellCabOut,true,null,cellInventoryInoutForm.getUuid());
        }
        UseInventoryInoutForm useInventoryInoutForm=getUseInventoryInoutForm(cellInventoryInoutForm);
        if (useInventoryInoutForm.getDetailList().size()>0){
            StorageInventoryInout storageInventoryInout=storageInventoryInoutDetailService.inventoryOut(useInventoryInoutForm.getDetailList(), StorageInventoryInout.BusinessType.exhibit,useInventoryInoutForm.getDeviceCode(),StorageInventoryInout.BusinessDetailType.newOut,UseInventoryInout.BusinessType.newOut);
            cellInventoryInout.getLabelCodeList().addAll(storageInventoryInout.getLabelCodeList());
        }
        Long storesRequisitionId=cellInventoryInoutForm.getStoresRequisitionId();
        if (storesRequisitionId!=null){
            storesRequisitionService.requisitionProductRecord(storesRequisitionId,getRequestProduct(cellInventoryInoutForm.getDetailList()));
        }
        return cellInventoryInout;
    }

    private CellInventoryInoutForm getCellInventoryInoutForm(CellInventoryInoutForm cellInventoryInoutForm){
        CellInventoryInoutForm cellInventoryInoutFormResult=new CellInventoryInoutForm();
        BeanUtils.copyProperties(cellInventoryInoutForm,cellInventoryInoutFormResult);

        List<CellInventoryInoutDetailForm> detailList=new ArrayList<>();
        cellInventoryInoutForm.getDetailList().forEach(e->{
            if (CellInventoryInoutDetailForm.CabType.saleCab.equals(e.getCabType())){
                detailList.add(e);
            }
        });
        cellInventoryInoutFormResult.setDetailList(detailList);
        return cellInventoryInoutFormResult;
    }

    private UseInventoryInoutForm getUseInventoryInoutForm(CellInventoryInoutForm cellInventoryInoutForm){
        UseInventoryInoutForm useInventoryInoutForm=new UseInventoryInoutForm();
        BeanUtils.copyProperties(cellInventoryInoutForm,useInventoryInoutForm);
        List<UseInventoryInoutDetailForm> detailList=new ArrayList<>();
        cellInventoryInoutForm.getDetailList().forEach(e->{
            if (CellInventoryInoutDetailForm.CabType.tempCab.equals(e.getCabType())){
                UseInventoryInoutDetailForm useInventoryInoutDetailForm=new UseInventoryInoutDetailForm();
                BeanUtils.copyProperties(e,useInventoryInoutDetailForm);
                detailList.add(useInventoryInoutDetailForm);
            }
        });
        useInventoryInoutForm.setDetailList(detailList);
        if (detailList.size()>0){
            useInventoryInoutForm.getDetailList().get(0).setWorkOrderId(useInventoryInoutForm.getWorkOrderId());
            useInventoryInoutForm.getDetailList().get(0).setProcessId(useInventoryInoutForm.getProcessId());
        }
        return useInventoryInoutForm;
    }

    @Override
    @Transactional
    public CellInventoryInout inventoryOut(List<CellInventoryInoutDetailForm> list,String deviceCode,CellInventoryInout.BusinessType businessType, UseInventoryInout.BusinessType useBusinessType,Boolean byPassword,Long storesRequisitionId,String uuid) {
        if(StringUtils.isNotBlank(uuid)){
            QueryWrapper<CellInventoryInout> inventoryQueryWrapper = new QueryWrapper<CellInventoryInout>();
            inventoryQueryWrapper.eq("uuid",uuid);
            CellInventoryInout tempCellInventoryInout = inventoryInoutService.getOne(inventoryQueryWrapper);
            if(null != tempCellInventoryInout){
                log.error("领新失败: 重复提交!");
                throw new BusinessException(3003,"领新失败: 重复提交!");
            }
        }
        //        setDefaultVal(list);
        if (StringUtils.isBlank(deviceCode)){
            deviceCode=list.get(0).getDeviceCode();
        }
        setDefaultVal4Out(list);
        //校验权限组
        //if (byPassword==null||!byPassword){
        //    verifyPermissions(list);
        //}
        Long enterpriseId=JwtUtils.getEnterpriseId();
        String enterpriseCode=JwtUtils.getEnterpriseCode();
        String enterpriseName=JwtUtils.getEnterpriseName();
        String roleName=JwtUtils.getRoleName();
        Long departmentId=JwtUtils.getDepartmentId();
        String departmentName=JwtUtils.getDepartmentName();
        String channelCode=JwtUtils.getChannelCode();
        Long roleId=JwtUtils.getRoleId();
//        SystemRuleInfo systemRuleInfo=systemRuleInfoService.getOne(new QueryWrapper<SystemRuleInfo>());
        SystemRuleInfo systemRuleInfo=systemRuleInfoService.getRuleInfo();
        boolean warehouseInventoryFlag=false;
        if (systemRuleInfo!=null){
            warehouseInventoryFlag=systemRuleInfo.getWarehouseInventoryFlag();
        }
        if (systemRuleInfo!=null&&systemRuleInfo.getTotalFlag()){
            saveInventoryOutAmount(list,systemRuleInfo.getTotal());
        }
        if (warehouseInventoryFlag){
            cabInventoryProductService.inventoryOut(list);
        }
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMdd");
        CellInventoryInout cellInventoryInout=new CellInventoryInout();
        String code=dynamicService.getDayNextCode("cab_cell_inventory_inout");
        String day=simpleDateFormat.format(new Date());
        cellInventoryInout.setCode("OU-"+day+"-"+code);
        cellInventoryInout.setDay(Integer.valueOf(day));
        cellInventoryInout.setUuid(uuid);
        cellInventoryInout.setNo(Integer.valueOf(code));
        cellInventoryInout.setCreator(JwtUtils.getLoginUserId());
        cellInventoryInout.setCreatorName(JwtUtils.getLoginUsername());
        cellInventoryInout.setType(CellInventoryInout.Type.out);
        cellInventoryInout.setDeviceCode(deviceCode);
        cellInventoryInout.setCompanyId(enterpriseId);
        cellInventoryInout.setBusinessType(businessType);
        cellInventoryInout.setRemark(businessType.getDesc());
        cellInventoryInout.setWorkOrderId(list.get(0).getWorkOrderId());
        cellInventoryInout.setProcessId(list.get(0).getProcessId());
        cellInventoryInout.setDepartmentId(departmentId);
        cellInventoryInout.setDepartmentName(departmentName);
        cellInventoryInout.setCostCenter(JwtUtils.getCostCenter());
        cellInventoryInout.setRoleName(roleName);
        cellInventoryInout.setEnterpriseCode(enterpriseCode);
        cellInventoryInout.setTotal(getTotal(list));
        cellInventoryInout.setChannelCode(channelCode);
        cellInventoryInout.setMainCabCode(list.get(0).getMainCabCode());
        cellInventoryInout.setRoleId(roleId);
        CellInventoryOutSeq cellInventoryOutSeq=new CellInventoryOutSeq();
        cellInventoryOutSeqService.insert(cellInventoryOutSeq);
        Long id=cellInventoryOutSeqService.getId();
        String orderCode= StringUtils.leftPad(id.toString(),10,"0");
        cellInventoryInout.setOrderCode(orderCode);

        inventoryInoutService.save(cellInventoryInout);
//        saveSkuDevice(list,deviceCode);

        OrderDevice orderDevice=new OrderDevice();
        orderDevice.setOrderCode(orderCode);
        orderDevice.setDeviceCode(deviceCode);
        orderDeviceService.save(orderDevice);

        saveDetail(list,cellInventoryInout.getId(),CellInventoryInout.Type.out.name());
        log.info("换新或领新执行inventoryInoutService.save得到cellInventoryInoutId："+cellInventoryInout.getId());
        UseInventoryInout useInventoryInout=useInventoryInoutDetailService.inventoryIn(list,cellInventoryInout.getId(),useBusinessType,deviceCode,orderCode,null,cellInventoryInout.getId());
        cellInventoryInout.setLabelCodeList(useInventoryInout.getLabelCodeList());
        //异步同步数据
        CellInventoryInoutForm cellInventoryInoutForm = new CellInventoryInoutForm();
        cellInventoryInoutForm.setDetailList(list);

        cellInventoryInout.setEnterpriseCode(enterpriseCode);

        // 添加刀具生命周期  --  售刀柜领新
        CutterLifeCycle.Status cutterLifeCycleStatus = null;
        if(useBusinessType.equals(UseInventoryInout.BusinessType.cellCabOut)){
            cutterLifeCycleStatus = CutterLifeCycle.Status.getFresh;
        }else if(useBusinessType.equals(UseInventoryInout.BusinessType.cellCabOutByOldNew)){
            cutterLifeCycleStatus = CutterLifeCycle.Status.tradeIn;
        }
        if(cutterLifeCycleStatus != null){
            List<String> labelCodeList = useInventoryUserKnifeService.listByParentCodes(useInventoryInout.getLabelCodeList());
            cutterLifeCycleService.addLifeCycle(labelCodeList, cutterLifeCycleStatus, null, useBusinessType, cellInventoryInout.getCode(), deviceCode);
        }

        log.info("开始领新数据同步...");
        sendMsg(cellInventoryInout,cellInventoryInoutForm);
        if (storesRequisitionId!=null){
            storesRequisitionService.requisitionProductRecord(storesRequisitionId,getRequestProduct(list));
        }

        //发送缺货告警邮件
        try {
            log.info("开始处理告警邮件发送,领取产品信息:{}",list);
            for (CellInventoryInoutDetailForm inoutDetailForm : list) {//领取产品
                String mainCabCode = inoutDetailForm.getMainCabCode();
                String cabCode = inoutDetailForm.getCabCode();
                String skuCode = inoutDetailForm.getSkuCode();

                QueryWrapper<CabAlarmSettings> queryWrapper =new QueryWrapper<>();
                queryWrapper.eq("cab_code",mainCabCode);
                queryWrapper.eq("sku_code",skuCode);
                CabAlarmSettings cabAlarmSettings = cabAlarmSettingsService.getOne(queryWrapper);
                log.info("物料告警信息:{}",cabAlarmSettings);

                Integer totalQuantity;//剩余库存总数
                Integer alarmSettingNum;//告警数量
                Integer lackQuantity;//缺货数量
                totalQuantity = cellInventorySpaceService.getSumByParams(mainCabCode,cabCode,skuCode);

                if (ObjectUtils.isNotEmpty(cabAlarmSettings)){
                    alarmSettingNum = cabAlarmSettings.getAlarmStock().intValue();

                    log.info("进入物料产品告警预值判断,告警数量:{},剩余库存总数:{}",alarmSettingNum,totalQuantity);
                    if (totalQuantity < alarmSettingNum) {
                        lackQuantity = (totalQuantity - alarmSettingNum) * -1;
                        log.info("缺货数量:{}",lackQuantity);
                        sendAlarmMail(alarmSettingNum,totalQuantity,lackQuantity,mainCabCode,cabCode,skuCode,JwtUtils.getEnterpriseName(),JwtUtils.getEnterpriseCode());
                    }
                } else {
                    alarmSettingNum = systemRuleInfo.getDefaultAlarmStock();

                    log.info("进入全局告警值预值判断,告警数量:{},剩余库存总数:{}",alarmSettingNum,totalQuantity);
                    if (totalQuantity < alarmSettingNum) {
                        lackQuantity = (totalQuantity - alarmSettingNum) * -1;
                        log.info("缺货数量:{}",lackQuantity);
                        sendAlarmMail(alarmSettingNum,totalQuantity,lackQuantity,mainCabCode,cabCode,skuCode,JwtUtils.getEnterpriseName(),JwtUtils.getEnterpriseCode());
                    }
                }

            }
        } catch (Exception e) {
            log.error("告警邮件发送失败：",e);
        } finally {
            return cellInventoryInout;
        }

    }


    public void sendAlarmMail(Integer alarmQuantity,Integer surplusQuantity,Integer lackQuantity,String mainCabCode,String cabCode,String skuCode,String enterpriseName,String enterpriseCode) throws Exception {
        log.info("----进入sendAlarmMail方法----,企业编号:{}",enterpriseCode);
//        executorService.submit(() -> {
//            try {
        emailWithPreview(alarmQuantity,surplusQuantity,lackQuantity,mainCabCode,cabCode,skuCode,enterpriseName,enterpriseCode);
//            } catch (Exception e) {
//                log.error("sendMail fail=>{}",e);
//            }
//        });
    }

    public void emailWithPreview(Integer alarmQuantity,Integer surplusQuantity,Integer lackQuantity,String mainCabCode,String cabCode,String skuCode,String enterpriseName,String enterpriseCode) throws Exception {
        log.info("进入emailWithPreview()，开始处理告警邮件信息 ");
//        DynamicDataSource.name.set(enterpriseCode.toLowerCase());

        HashMap map = mailInfo.queryInfo();
        String userName = map.get("send_account").toString();
        String password = map.get("email_password").toString();
        String host = map.get("smtp_server").toString();
        String port = map.get("port").toString();
        String ssl = map.get("is_ssl").toString();

        //查询主柜
        Cabinet cabinet = cabinetService.getOne(new LambdaQueryWrapper<Cabinet>().eq(Cabinet::getCabCode, mainCabCode));

        // 库存告警管理员
        List<SystemRuleInfo> list = systemRuleInfoService.list();
        log.info("库存告警管理员信息:{}",list);

        if (CollectionUtil.isNotEmpty(list)) {
            if (StringUtils.isNotBlank(list.get(0).getInventoryManageUserId())) {
                String[] strId = list.get(0).getInventoryManageUserId().split(",");
                for (String item : strId) {
                    log.info("库存告警员ID:{}",item);
                    JsonResult<UserVO> userInfo = userClient.getUserInfo(Long.valueOf(item));

                    log.info("发送邮箱账号:{},密码:{}",userName,password);
                    log.info("告警员用户信息:{},用户邮箱:{}",userInfo,userInfo.getData().getEmail());
                    if (StringUtils.isNotBlank(userInfo.getData().getEmail())) {

                        StringBuffer content = new StringBuffer();
                        content.append("<div style='font-size: 18px;min-height: 180px;height: auto;min-height:350px;background-color: #f5f5f7;box-shadow: 0 0 10px 3px #0000001a;border-radius: 20px;box-sizing: border-box;padding:30px;margin: 20px;'>");
                        content.append("<div style='text-align: left;min-height: 180px; margin: 10px 0;height: auto; padding-left: 2em;'>");
                        content.append("<p>公司名称为"+enterpriseName+"("+enterpriseCode+")"+"。</p>");
                        content.append("<p>主柜编号为"+mainCabCode+"。</p>");
                        content.append("<p>柜子编号为"+cabCode+"。</p>");
                        content.append("<p>物料编码为"+skuCode+"。</p>");
                        content.append("<p>告警设置数量为"+alarmQuantity+"（现剩余库存数量为"+surplusQuantity+"，缺货数量为"+lackQuantity+"）。</p>");
                        content.append("<p>主柜位置在"+cabinet.getWorkshopLocation()+"。</p>");
                        content.append("</div>");
                        content.append("</div>");
                        senderConfig.sendMail(userName,password,host,ssl, Integer.valueOf(port),userInfo.getData().getEmail(),"主题：缺货告警提醒",content.toString());

                        log.info("发送邮箱结束");
                    }
                }
            }
        }



    }


    private void  setDefaultVal4Out(List<CellInventoryInoutDetailForm> list){
        list.forEach(e->{
            if (CellInventoryInoutDetailForm.CabType.saleCab.equals(e.getCabType())){
                List<CellInventorySpace> cellInventorySpaces=cellInventorySpaceService.list(new QueryWrapper<CellInventorySpace>().eq("cab_code",e.getCabCode()).eq("space_code",e.getSpaceCode()));
                if (cellInventorySpaces.size()>0){

                    if (e.getQuantityPackUnit()==null||e.getQuantityPackUnit()==0){
                        e.setQuantityPackUnit(cellInventorySpaces.get(0).getQuantityPackUnit());
                    }
                    if (e.getPackId()==null||e.getPackId()==0){
                        e.setPackId(cellInventorySpaces.get(0).getPackId());
                    }
                    if (StringUtils.isBlank(e.getPackName())){
                        e.setPackName(cellInventorySpaces.get(0).getPackName());
                    }
                    if (StringUtils.isBlank(e.getUnitName())){
                        e.setUnitName(cellInventorySpaces.get(0).getUnitName());
                    }
                }
            }else if(CellInventoryInoutDetailForm.CabType.tempCab.equals(e.getCabType())){

            }
        });

    }

    @Override
    @Transactional
    public void inventoryOutEmpty(List<CellInventoryInoutDetailForm> list,String deviceCode,CellInventoryInout.BusinessType businessType, UseInventoryInout.BusinessType useBusinessType) {
        for (CellInventoryInoutDetailForm cellInventoryInoutDetailForm:list){
            List<CellInventorySpace> cellInventorySpaceVOS=cellInventorySpaceService.list(new QueryWrapper<CellInventorySpace>().eq("cab_code",cellInventoryInoutDetailForm.getCabCode()).eq("space_code",cellInventoryInoutDetailForm.getSpaceCode()));
            if (cellInventorySpaceVOS.get(0).getQuantity()>0){
                throw new BusinessException("有库存不能清空");
            }
            cellInventorySpaceService.removeById(cellInventorySpaceVOS.get(0).getId());
            //查询cab_cell_single_inventory_product暂存柜产品库存(单个柜子)是否还有库存，没有库存清空
            List<CellSingleInventoryProduct> cellSingleInventoryProductList = cellSingleInventoryProductService.list(new QueryWrapper<CellSingleInventoryProduct>().eq("cab_code",cellInventoryInoutDetailForm.getCabCode()).eq("sku_code",cellInventorySpaceVOS.get(0).getSkuCode()));
            Integer quantity = cellSingleInventoryProductList.stream().mapToInt(CellSingleInventoryProduct::getQuantity).sum();
            if(quantity <= 0 ) {
                for (CellSingleInventoryProduct cellSingleInventoryProduct : cellSingleInventoryProductList){
                    cellSingleInventoryProductService.removeById(cellSingleInventoryProduct.getId());
                }
            }
        }
    }

    private List<StoresRequisitionProductForm> getRequestProduct(List<CellInventoryInoutDetailForm> list){
        List<StoresRequisitionProductForm> resultList=new ArrayList<>();
        Map<String,StoresRequisitionProductForm> resultMap=new HashMap<>();
        for (CellInventoryInoutDetailForm cellInventoryInoutDetailForm:list){
            StoresRequisitionProductForm temp=resultMap.get(cellInventoryInoutDetailForm.getSkuCode());
            if (temp==null){
                StoresRequisitionProductForm storesRequisitionProductForm=new StoresRequisitionProductForm();
                storesRequisitionProductForm.setSkuCode(cellInventoryInoutDetailForm.getSkuCode());
                storesRequisitionProductForm.setNeckQuantity(cellInventoryInoutDetailForm.getQuantity());
                storesRequisitionProductForm.setId(cellInventoryInoutDetailForm.getRequestProductId());
                storesRequisitionProductForm.setQuantityPackUnit(cellInventoryInoutDetailForm.getQuantityPackUnit());
                storesRequisitionProductForm.setPackName(cellInventoryInoutDetailForm.getPackName());
                storesRequisitionProductForm.setPackId(cellInventoryInoutDetailForm.getPackId());
                storesRequisitionProductForm.setUnitName(cellInventoryInoutDetailForm.getUnitName());
                resultMap.put(cellInventoryInoutDetailForm.getSkuCode(),storesRequisitionProductForm);
            }else{
                temp.setNeckQuantity(temp.getNeckQuantity()+cellInventoryInoutDetailForm.getQuantity());
                resultMap.put(cellInventoryInoutDetailForm.getSkuCode(),temp);
            }
        }
        resultMap.keySet().forEach(item->{
            resultList.add(resultMap.get(item));
        });
        return resultList;
    }

    @Transactional
    void saveInventoryOutAmount(List<CellInventoryInoutDetailForm> list,BigDecimal settingAmount){
        Long creator=JwtUtils.getLoginUserId();
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMdd");
        String day=simpleDateFormat.format(new Date());
        BigDecimal amount=getAmount(list);
        List<CellInventoryOutAmount> cellInventoryOutAmounts=cellInventoryOutAmountService.list(new QueryWrapper<CellInventoryOutAmount>().eq("creator",creator));
        if(cellInventoryOutAmounts.size()==0){
            if (settingAmount!=null&&settingAmount.doubleValue()>0&&settingAmount.subtract(amount).doubleValue()<0){
                throw new BusinessException("不能超过设置的每天每人领刀价值最大金额");
            }
            CellInventoryOutAmount cellInventoryOutAmount=new CellInventoryOutAmount();
            cellInventoryOutAmount.setCreator(creator);
            cellInventoryOutAmount.setDay(Integer.valueOf(day));
            cellInventoryOutAmount.setTotal(amount);
            cellInventoryOutAmountService.save(cellInventoryOutAmount);
        }else{
            CellInventoryOutAmount cellInventoryOutAmount4Update=new CellInventoryOutAmount();
            BigDecimal total=cellInventoryOutAmounts.get(0).getTotal();
            total=total.add(getAmount(list));
            cellInventoryOutAmount4Update.setTotal(total);
            cellInventoryOutAmount4Update.setId(cellInventoryOutAmounts.get(0).getId());
            if (Integer.valueOf(day).equals(cellInventoryOutAmounts.get(0).getDay())){
                cellInventoryOutAmount4Update.setDay(Integer.valueOf(day));
                cellInventoryOutAmount4Update.setTotal(amount);
                total=amount;
            }
            if (settingAmount!=null&&settingAmount.doubleValue()>0&&settingAmount.subtract(total).doubleValue()<0){
                throw new BusinessException("不能超过设置的每天每人领刀价值最大金额");
            }
            cellInventoryOutAmountService.updateById(cellInventoryOutAmount4Update);
        }

    }

    private BigDecimal getAmount(List<CellInventoryInoutDetailForm> list){
        BigDecimal amount=new BigDecimal(0);
        if (CollectionUtil.isNotEmpty(list)){
            for (CellInventoryInoutDetailForm cellInventoryInoutDetailForm:list){
                if (cellInventoryInoutDetailForm.getMarketPrice()!=null){
                    amount=amount.add(BigDecimal.valueOf(cellInventoryInoutDetailForm.getQuantity()).multiply(cellInventoryInoutDetailForm.getMarketPrice()));
                }
            }
        }
        return amount;
    }

    @Override
    @Transactional
    public CellInventoryInout inventoryOut4Simple(OrderReceiveLoadForm orderReceiveLoadForm) {
        setDefaultVal(orderReceiveLoadForm);
        List<OrderReceiveLoadDetailForm> detailList=new ArrayList<>();
        OrderReceiveLoadDetailForm orderReceiveLoadDetailForm=new OrderReceiveLoadDetailForm();
        BeanUtils.copyProperties(orderReceiveLoadForm,orderReceiveLoadDetailForm);
        orderReceiveLoadDetailForm.setCabCode(orderReceiveLoadForm.getCabCode());
        orderReceiveLoadDetailForm.setSkuCode(orderReceiveLoadForm.getSkuCode());
        orderReceiveLoadDetailForm.setSpaceCode(orderReceiveLoadForm.getSpaceCode());
        orderReceiveLoadDetailForm.setQuantity(orderReceiveLoadForm.getQuantity());
        detailList.add(orderReceiveLoadDetailForm);
        orderReceiveLoadForm.setDetailList(detailList);
        return this.inventoryOut4BatchSimple(orderReceiveLoadForm);
    }
    @Override
    @Transactional
    public CellInventoryInout inventoryOut4BatchSimple(OrderReceiveLoadForm orderReceiveLoadForm) {
        setDefaultVal(orderReceiveLoadForm);
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMdd");
        Long enterpriseId=JwtUtils.getEnterpriseId();
        String enterpriseCode=JwtUtils.getEnterpriseCode();
        String departmentName=JwtUtils.getDepartmentName();
        Long departmentId=JwtUtils.getDepartmentId();
        String roleName=JwtUtils.getRoleName();
        Long roleId=JwtUtils.getRoleId();
        String channelCode=JwtUtils.getChannelCode();
        CellInventoryInoutForm cellInventoryInoutForm=new CellInventoryInoutForm();
//        cellInventoryInoutForm.setReceiveLoadId(orderReceiveLoad.getId());
        List<CellInventoryInoutDetailForm> list=new ArrayList<>();
//        CellInventoryInoutDetailForm cellInventoryInoutDetailForm=new CellInventoryInoutDetailForm();
//        cellInventoryInoutDetailForm.setCabCode(orderReceiveLoadForm.getCabCode());
//        cellInventoryInoutDetailForm.setSkuCode(orderReceiveLoadForm.getSkuCode());
//        cellInventoryInoutDetailForm.setSpaceCode(orderReceiveLoadForm.getSpaceCode());
//        cellInventoryInoutDetailForm.setQuantity(orderReceiveLoadForm.getQuantity());
//
//        list.add(cellInventoryInoutDetailForm);

        for(OrderReceiveLoadDetailForm orderReceiveLoadDetailForm:orderReceiveLoadForm.getDetailList()){
            CellInventoryInoutDetailForm cellInventoryInoutDetailForm=new CellInventoryInoutDetailForm();
            cellInventoryInoutDetailForm.setCabCode(orderReceiveLoadDetailForm.getCabCode());
            cellInventoryInoutDetailForm.setSkuCode(orderReceiveLoadDetailForm.getSkuCode());
            cellInventoryInoutDetailForm.setSpaceCode(orderReceiveLoadDetailForm.getSpaceCode());
            cellInventoryInoutDetailForm.setQuantity(orderReceiveLoadDetailForm.getQuantity());
            List<CellInventorySpace> cellInventorySpaces=cellInventorySpaceService.list(new QueryWrapper<CellInventorySpace>().eq("cab_code",orderReceiveLoadDetailForm.getCabCode()).eq("space_code",orderReceiveLoadDetailForm.getSpaceCode()));
            if (cellInventorySpaces.size()>0){
                cellInventoryInoutDetailForm.setQuantityPackUnit(cellInventorySpaces.get(0).getQuantityPackUnit());
                if (cellInventoryInoutDetailForm.getQuantityPackUnit()==null){
                    cellInventoryInoutDetailForm.setQuantityPackUnit(1);
                }
                cellInventoryInoutDetailForm.setPackName(cellInventorySpaces.get(0).getPackName());
                cellInventoryInoutDetailForm.setPackId(cellInventorySpaces.get(0).getPackId());
                cellInventoryInoutDetailForm.setUnitName(cellInventorySpaces.get(0).getUnitName());
                orderReceiveLoadDetailForm.setQuantityPackUnit(cellInventoryInoutDetailForm.getQuantityPackUnit());
                orderReceiveLoadDetailForm.setPackName(cellInventoryInoutDetailForm.getPackName());
                orderReceiveLoadDetailForm.setPackId(cellInventoryInoutDetailForm.getPackId());
                orderReceiveLoadDetailForm.setUnitName(cellInventoryInoutDetailForm.getUnitName());

                orderReceiveLoadDetailForm.setQuantityPack(cellInventoryInoutDetailForm.getQuantityPackUnit()*orderReceiveLoadDetailForm.getQuantity());
            }
            list.add(cellInventoryInoutDetailForm);
        }
        cellInventoryInoutForm.setDetailList(list);


        CellInventoryInout cellInventoryInout=new CellInventoryInout();
        String code=dynamicService.getDayNextCode("cab_cell_inventory_inout");
        String day=simpleDateFormat.format(new Date());
        cellInventoryInout.setCode("OU-"+day+"-"+code);
        cellInventoryInout.setDay(Integer.valueOf(day));

        cellInventoryInout.setNo(Integer.valueOf(code));
        cellInventoryInout.setCreator(JwtUtils.getLoginUserId());
        cellInventoryInout.setCreatorName(JwtUtils.getLoginUsername());
        cellInventoryInout.setType(CellInventoryInout.Type.unload);
        cellInventoryInout.setBusinessType(CellInventoryInout.BusinessType.outByUnload);
//        cellInventoryInout.setDeviceCode(deviceCode);
        cellInventoryInout.setCompanyId(enterpriseId);
        cellInventoryInout.setEnterpriseCode(enterpriseCode);
        cellInventoryInout.setRemark(CellInventoryInout.BusinessType.outByUnload.getDesc());
        cellInventoryInout.setTotal(getTotal(list));
        cellInventoryInout.setDepartmentName(departmentName);
        cellInventoryInout.setRoleName(roleName);
        cellInventoryInout.setDepartmentId(departmentId);
        cellInventoryInout.setRoleId(roleId);
        cellInventoryInout.setChannelCode(channelCode);
//        CellInventoryOutSeq cellInventoryOutSeq=new CellInventoryOutSeq();
//        cellInventoryOutSeqService.insert(cellInventoryOutSeq);
//        Long id=cellInventoryOutSeqService.getId();
//        String orderCode= StringUtils.leftPad(id.toString(),10,"0");
//        cellInventoryInout.setOrderCode(orderCode);
//        cellInventoryInout.setRemark("自主下货");
        inventoryInoutService.save(cellInventoryInout);
//        saveSkuDevice(list,deviceCode);

//        OrderDevice orderDevice=new OrderDevice();
//        orderDevice.setOrderCode(orderCode);
//        orderDevice.setDeviceCode(deviceCode);
//        orderDeviceService.save(orderDevice);

        OrderReceiveLoad orderReceiveLoad=new OrderReceiveLoad();
        BeanUtils.copyProperties(orderReceiveLoadForm,orderReceiveLoad);
//        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMdd");
        code=dynamicService.getDayNextCode("ord_order_receive_load");
//        String day=simpleDateFormat.format(new Date());
        orderReceiveLoad.setCode("RLS-"+day+"-"+code);
        orderReceiveLoad.setDay(Integer.valueOf(day));
        orderReceiveLoad.setNo(Integer.valueOf(code));
        orderReceiveLoad.setCreator(JwtUtils.getLoginUserId());
        orderReceiveLoad.setCreatorName(JwtUtils.getLoginUsername());
        orderReceiveLoad.setDepartmentName(departmentName);
        orderReceiveLoad.setRoleName(roleName);
        orderReceiveLoad.setDepartmentId(departmentId);
        orderReceiveLoad.setRoleId(roleId);
        orderReceiveLoad.setChannelCode(channelCode);
        orderReceiveLoadService.save(orderReceiveLoad);
        saveReceiveLoadDetail(orderReceiveLoadForm,orderReceiveLoad.getId());
        cellInventoryInout.setReceiveLoadId(orderReceiveLoad.getId());

        saveDetail(list,cellInventoryInout.getId(),CellInventoryInout.Type.unload.name());
//        useInventoryInoutDetailService.inventoryIn(list,cellInventoryInout.getId(),UseInventoryInout.BusinessType.cellCabReceive,null,null);
        //异步同步数据
//        CellInventoryInoutForm cellInventoryInoutForm = new CellInventoryInoutForm();
        cellInventoryInoutForm.setDetailList(list);
        sendMsg(cellInventoryInout,cellInventoryInoutForm);
        return cellInventoryInout;
    }

    @Transactional
    void saveReceiveLoadDetail(OrderReceiveLoadForm orderReceiveLoadForm,Long loadId){
        String enterpriseCode=JwtUtils.getEnterpriseCode();
        String channelCode=JwtUtils.getEnterpriseCode();
        if(CollectionUtil.isNotEmpty(orderReceiveLoadForm.getDetailList())){
            for (OrderReceiveLoadDetailForm orderReceiveLoadDetailForm:orderReceiveLoadForm.getDetailList()){
                OrderReceiveLoadDetail orderReceiveLoadDetail=new OrderReceiveLoadDetail();
                BeanUtils.copyProperties(orderReceiveLoadDetailForm,orderReceiveLoadDetail);
                orderReceiveLoadDetail.setLoadId(loadId);
                orderReceiveLoadDetail.setEnterpriseCode(enterpriseCode);
                orderReceiveLoadDetail.setChannelCode(channelCode);
                orderReceiveLoadDetailService.save(orderReceiveLoadDetail);
            }
        }
    }

    @Transactional
    void saveSkuDevice(List<CellInventoryInoutDetailForm> list,String deviceCode){
        for (CellInventoryInoutDetailForm cellInventoryInoutDetailForm:list){
            SkuDevice skuDevice=new SkuDevice();
            int count=skuDeviceService.count(new QueryWrapper<SkuDevice>().eq("sku_code",cellInventoryInoutDetailForm.getSkuCode()).eq("device_code",deviceCode));
            if(count==0){
                skuDevice.setCabCode(cellInventoryInoutDetailForm.getCabCode());
                skuDevice.setSkuCode(cellInventoryInoutDetailForm.getSkuCode());
                skuDevice.setDeviceCode(deviceCode);
                skuDeviceService.save(skuDevice);
            }
        }
    }

    @Override
    @Transactional
    public void inventoryIn(CellInventoryInoutForm cellInventoryInoutForm) {
//        SystemRuleInfo systemRuleInfo=systemRuleInfoService.getOne(new QueryWrapper<SystemRuleInfo>());
        SystemRuleInfo systemRuleInfo=systemRuleInfoService.getRuleInfo();
        boolean warehouseInventoryFlag=false;
        if (systemRuleInfo!=null){
            warehouseInventoryFlag=systemRuleInfo.getWarehouseInventoryFlag();
        }
        Long enterpriseId=JwtUtils.getEnterpriseId();
        String enterpriseCode=JwtUtils.getEnterpriseCode();
        Long departmentId=JwtUtils.getDepartmentId();
        String departmentName=JwtUtils.getDepartmentName();
        String roleName=JwtUtils.getRoleName();
        String channelCode=JwtUtils.getChannelCode();
        Long roleId=JwtUtils.getRoleId();
        if (CollectionUtils.isEmpty(cellInventoryInoutForm.getDetailList())){
            throw new BusinessException("缺少上货明细数据");
        }
        OrderReceive orderReceive=receiveService.getById(cellInventoryInoutForm.getReceiveId());
        if (orderReceive==null){
            throw new BusinessException("未找到领货记录");
        }
        List<OrderReceiveDetail> receiveDetails=receiveDetailService.list(new QueryWrapper<OrderReceiveDetail>().eq("receive_id",cellInventoryInoutForm.getReceiveId()).eq("sku_code",cellInventoryInoutForm.getDetailList().get(0).getSkuCode()));
        if (receiveDetails.size()==0){
            throw new BusinessException("未找到领货明细业务数据");
        }
        if (warehouseInventoryFlag){
//            cabInventoryProductService.inventoryOut(cellInventoryInoutForm.getDetailList());
        }

        Long creator=JwtUtils.getLoginUserId();
        String creatorName=JwtUtils.getLoginUsername();
        CellInventoryInout cellInventoryInout=new CellInventoryInout();
        BeanUtils.copyProperties(cellInventoryInoutForm,cellInventoryInout);
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMdd");

        String code=dynamicService.getDayNextCode("cab_cell_inventory_inout");
        String day=simpleDateFormat.format(new Date());
        cellInventoryInout.setCode("IN-"+day+"-"+code);
        cellInventoryInout.setDay(Integer.valueOf(day));
        cellInventoryInout.setNo(Integer.valueOf(code));
        cellInventoryInout.setCreator(creator);
        cellInventoryInout.setCreatorName(creatorName);
        cellInventoryInout.setType(CellInventoryInout.Type.in);
        cellInventoryInout.setDepartmentId(departmentId);
        cellInventoryInout.setDepartmentName(departmentName);
        cellInventoryInoutForm.setCreator(creator);
        cellInventoryInoutForm.setCreatorName(creatorName);
//        saveReceiveLoad(cellInventoryInoutForm);

        saveReceiveLoad(cellInventoryInoutForm);

        OrderReceiveLoad orderReceiveLoad=new OrderReceiveLoad();
//        BeanUtils.copyProperties(orderReceiveLoadForm,orderReceiveLoad);
//        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMdd");
        code=dynamicService.getDayNextCode("ord_order_receive_load");
//        String day=simpleDateFormat.format(new Date());
        orderReceiveLoad.setCode("RL-"+day+"-"+code);
        orderReceiveLoad.setDay(Integer.valueOf(day));
        orderReceiveLoad.setNo(Integer.valueOf(code));
        orderReceiveLoad.setCreator(JwtUtils.getLoginUserId());
        orderReceiveLoad.setCreatorName(JwtUtils.getLoginUsername());
        orderReceiveLoad.setReceiveId(cellInventoryInoutForm.getReceiveId());
        orderReceiveLoad.setReceiveDetailId(receiveDetails.get(0).getId());
        orderReceiveLoad.setSkuCode(cellInventoryInoutForm.getDetailList().get(0).getSkuCode());
        orderReceiveLoad.setCabCode(cellInventoryInoutForm.getDetailList().get(0).getCabCode());
        orderReceiveLoad.setSpaceCode(cellInventoryInoutForm.getDetailList().get(0).getSpaceCode());

        orderReceiveLoad.setSkuId(cellInventoryInoutForm.getDetailList().get(0).getSkuId());
        orderReceiveLoad.setCabId(cellInventoryInoutForm.getDetailList().get(0).getCabId());
        orderReceiveLoad.setSpaceId(cellInventoryInoutForm.getDetailList().get(0).getSpaceId());
        orderReceiveLoad.setQuantity(cellInventoryInoutForm.getDetailList().get(0).getQuantity());
        orderReceiveLoad.setType(OrderReceiveLoad.Type.jsonCreator(orderReceive.getType().name()));
        orderReceiveLoad.setEnterpriseCode(enterpriseCode);
        orderReceiveLoad.setDepartmentName(departmentName);
        orderReceiveLoad.setRoleName(roleName);
        orderReceiveLoad.setDepartmentId(departmentId);
        orderReceiveLoad.setChannelCode(channelCode);
        orderReceiveLoad.setRoleId(roleId);
        orderReceiveLoadService.save(orderReceiveLoad);
        cellInventoryInout.setReceiveLoadId(orderReceiveLoad.getId());

        cellInventoryInout.setCompanyId(enterpriseId);
        cellInventoryInout.setEnterpriseCode(enterpriseCode);
        cellInventoryInout.setTotal(getTotal(cellInventoryInoutForm.getDetailList()));
        cellInventoryInout.setDepartmentName(departmentName);
        cellInventoryInout.setRoleName(roleName);
        cellInventoryInout.setChannelCode(channelCode);
        cellInventoryInout.setRoleId(roleId);
        inventoryInoutService.save(cellInventoryInout);
        saveDetail(cellInventoryInoutForm.getDetailList(),cellInventoryInout.getId(),CellInventoryInout.Type.in.name());
        //异步同步数据
        cellInventoryInout.setEnterpriseCode(enterpriseCode);
        sendMsg(cellInventoryInout,cellInventoryInoutForm);
    }

    private void setDefaultVal(OrderReceiveLoadForm orderReceiveLoadForm){
        if (orderReceiveLoadForm.getQuantityPackUnit()==null||orderReceiveLoadForm.getQuantityPackUnit()==0){
            orderReceiveLoadForm.setQuantityPackUnit(CabConstants.QUANTITY_PACK_UNIT);
        }
        if (orderReceiveLoadForm.getPackId()==null||orderReceiveLoadForm.getPackId()==0){
            orderReceiveLoadForm.setPackId(CabConstants.DEFAULT_PACK_ID);
        }
        if (StringUtils.isBlank(orderReceiveLoadForm.getPackName())){
            orderReceiveLoadForm.setPackName(CabConstants.DEFAULT_PACK_NAME);
        }
        if (StringUtils.isBlank(orderReceiveLoadForm.getUnitName())){
            orderReceiveLoadForm.setUnitName(CabConstants.DEFAULT_UNIT_NAME);
        }
        if (CollectionUtil.isNotEmpty(orderReceiveLoadForm.getDetailList())){
            orderReceiveLoadForm.getDetailList().forEach(e->{
                if (e.getQuantityPackUnit()==null||e.getQuantityPackUnit()==0){
                    e.setQuantityPackUnit(CabConstants.QUANTITY_PACK_UNIT);
                }
                if (e.getPackId()==null||e.getPackId()==0){
                    e.setPackId(CabConstants.DEFAULT_PACK_ID);
                }
                if (StringUtils.isBlank(e.getPackName())){
                    e.setPackName(CabConstants.DEFAULT_PACK_NAME);
                }
                if (StringUtils.isBlank(e.getUnitName())){
                    e.setUnitName(CabConstants.DEFAULT_UNIT_NAME);
                }
            });
        }
    }

    private void checkRequestParam(OrderReceiveLoadForm orderReceiveLoadForm){
        if (CollectionUtil.isEmpty(orderReceiveLoadForm.getDetailList())){
            throw new BusinessException("上货异常:请选择上货明细记录!");
        }
        for (OrderReceiveLoadDetailForm e:orderReceiveLoadForm.getDetailList()){
            if(null == orderReceiveLoadForm.getPackId() || orderReceiveLoadForm.getPackId().equals(0)){
                throw new BusinessException("上货异常:产品["+orderReceiveLoadForm.getSkuCode()+"],没有包装方式参数");
            }
        }
    }

    private void setDefaultValFromDb(OrderReceiveLoadForm orderReceiveLoadForm){
        ProductPackVO productPackVO ;
        if (orderReceiveLoadForm.getPackId()==null){
            productPackVO =productPackService.getDefaultPack();
        }else{
            productPackVO =productPackService.get4appById(orderReceiveLoadForm.getPackId());
        }
        Integer quantityPackUnit=CabConstants.QUANTITY_PACK_UNIT;
        Long packId=CabConstants.DEFAULT_PACK_ID;
        String packName=CabConstants.DEFAULT_PACK_NAME;
        String unitName=CabConstants.DEFAULT_UNIT_NAME;
        if (productPackVO!=null){
            if (productPackVO.getBaseRate()!=null&&productPackVO.getBaseRate()!=0){
                quantityPackUnit=productPackVO.getBaseRate();
            }
            if (productPackVO.getId()!=null){
                packId=productPackVO.getId();
            }
            if (StringUtils.isNotBlank(productPackVO.getName())){
                packName=productPackVO.getName();
            }
            if (StringUtils.isNotBlank(productPackVO.getPackUnitName())){
                unitName=productPackVO.getPackUnitName();
            }
        }
        if (orderReceiveLoadForm.getQuantityPackUnit()==null||orderReceiveLoadForm.getQuantityPackUnit()==0){
            orderReceiveLoadForm.setQuantityPackUnit(quantityPackUnit);
        }
        if (orderReceiveLoadForm.getPackId()==null||orderReceiveLoadForm.getPackId()==0){
            orderReceiveLoadForm.setPackId(packId);
        }
        if (StringUtils.isBlank(orderReceiveLoadForm.getPackName())){
            orderReceiveLoadForm.setPackName(packName);
        }
        if (StringUtils.isBlank(orderReceiveLoadForm.getUnitName())){
            orderReceiveLoadForm.setUnitName(unitName);
        }
        if (CollectionUtil.isNotEmpty(orderReceiveLoadForm.getDetailList())){
            for (OrderReceiveLoadDetailForm e:orderReceiveLoadForm.getDetailList()){

                if (e.getQuantityPackUnit()==null||e.getQuantityPackUnit()==0){
                    e.setQuantityPackUnit(quantityPackUnit);
                }
                if (e.getPackId()==null||e.getPackId()==0){
                    e.setPackId(packId);
                }
                if (StringUtils.isBlank(e.getPackName())){
                    e.setPackName(packName);
                }
                if (StringUtils.isBlank(e.getUnitName())){
                    e.setUnitName(unitName);
                }
            }
        }

    }

    private void setDefaultVal(List<CellInventoryInoutDetailForm> list){
        if (CollectionUtil.isNotEmpty(list)){
            list.forEach(e->{
                if (e.getQuantityPackUnit()==null||e.getQuantityPackUnit()==0){
                    e.setQuantityPackUnit(CabConstants.QUANTITY_PACK_UNIT);
                }
                if (e.getPackId()==null||e.getPackId()==0){
                    e.setPackId(CabConstants.DEFAULT_PACK_ID);
                }
                if (StringUtils.isBlank(e.getPackName())){
                    e.setPackName(CabConstants.DEFAULT_PACK_NAME);
                }
                if (StringUtils.isBlank(e.getUnitName())){
                    e.setUnitName(CabConstants.DEFAULT_UNIT_NAME);
                }
            });
        }
    }

    @Override
    @Transactional
    public void inventoryIn(OrderReceiveLoadForm orderReceiveLoadForm) {
        setDefaultVal(orderReceiveLoadForm);
        SystemRuleInfo systemRuleInfo=systemRuleInfoService.getOne(new QueryWrapper<SystemRuleInfo>());
        boolean warehouseInventoryFlag=false;
        if (systemRuleInfo!=null){
            warehouseInventoryFlag=systemRuleInfo.getWarehouseInventoryFlag();
        }
        Long departmentId=JwtUtils.getDepartmentId();
        String departmentName=JwtUtils.getDepartmentName();
        String enterpriseCode=JwtUtils.getEnterpriseCode();
        String channelCode=JwtUtils.getChannelCode();
        Long roleId=JwtUtils.getRoleId();

        String roleName=JwtUtils.getRoleName();


        List<OrderReceiveDetail> receiveDetails=receiveDetailService.list(new QueryWrapper<OrderReceiveDetail>().eq("receive_id",orderReceiveLoadForm.getReceiveId()).eq("sku_code",orderReceiveLoadForm.getSkuCode()));
        if (receiveDetails.size()==0){
            throw new BusinessException("未找到领货明细业务数据");
        }


        CellInventoryInoutForm cellInventoryInoutForm=new CellInventoryInoutForm();
//        cellInventoryInoutForm.setReceiveLoadId(orderReceiveLoad.getId());
        List<CellInventoryInoutDetailForm> detailList=new ArrayList<>();
        CellInventoryInoutDetailForm cellInventoryInoutDetailForm=new CellInventoryInoutDetailForm();
        cellInventoryInoutDetailForm.setCabCode(orderReceiveLoadForm.getCabCode());
        cellInventoryInoutDetailForm.setSkuCode(orderReceiveLoadForm.getSkuCode());
        cellInventoryInoutDetailForm.setSpaceCode(orderReceiveLoadForm.getSpaceCode());
        cellInventoryInoutDetailForm.setQuantity(orderReceiveLoadForm.getQuantity());
        cellInventoryInoutDetailForm.setReceiveDetailId(receiveDetails.get(0).getId());
        cellInventoryInoutDetailForm.setQuantityPackUnit(orderReceiveLoadForm.getQuantityPackUnit());
        cellInventoryInoutDetailForm.setPackId(orderReceiveLoadForm.getPackId());
        cellInventoryInoutDetailForm.setPackName(orderReceiveLoadForm.getPackName());
        cellInventoryInoutDetailForm.setUnitName(orderReceiveLoadForm.getUnitName());
        detailList.add(cellInventoryInoutDetailForm);
        cellInventoryInoutForm.setDetailList(detailList);
        if (warehouseInventoryFlag){
            cabInventoryProductService.checkWarehouseInventory4Load(cellInventoryInoutForm.getDetailList());
        }


        Long creator=JwtUtils.getLoginUserId();
        String creatorName=JwtUtils.getLoginUsername();
        CellInventoryInout cellInventoryInout=new CellInventoryInout();
        BeanUtils.copyProperties(cellInventoryInoutForm,cellInventoryInout);
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMdd");

        String code=dynamicService.getDayNextCode("cab_cell_inventory_inout");
        String day=simpleDateFormat.format(new Date());
        cellInventoryInout.setCode("IN-"+day+"-"+code);
        cellInventoryInout.setDay(Integer.valueOf(day));
        cellInventoryInout.setNo(Integer.valueOf(code));
        cellInventoryInout.setCreator(creator);
        cellInventoryInout.setCreatorName(creatorName);
        cellInventoryInout.setType(CellInventoryInout.Type.in);
        cellInventoryInout.setDepartmentId(departmentId);
        cellInventoryInout.setDepartmentName(departmentName);
        cellInventoryInout.setRoleName(roleName);
        cellInventoryInoutForm.setCreator(creator);
        cellInventoryInoutForm.setCreatorName(creatorName);
        saveReceiveLoad(cellInventoryInoutForm);

        OrderReceiveLoad orderReceiveLoad=new OrderReceiveLoad();
        BeanUtils.copyProperties(orderReceiveLoadForm,orderReceiveLoad);
//        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMdd");
        code=dynamicService.getDayNextCode("ord_order_receive_load");
//        String day=simpleDateFormat.format(new Date());
        orderReceiveLoad.setCode("RL-"+day+"-"+code);
        orderReceiveLoad.setDay(Integer.valueOf(day));
        orderReceiveLoad.setNo(Integer.valueOf(code));
        orderReceiveLoad.setCreator(JwtUtils.getLoginUserId());
        orderReceiveLoad.setCreatorName(JwtUtils.getLoginUsername());
        orderReceiveLoad.setReceiveDetailId(receiveDetails.get(0).getId());
        orderReceiveLoad.setEnterpriseCode(enterpriseCode);
        orderReceiveLoad.setDepartmentName(departmentName);
        orderReceiveLoad.setRoleName(roleName);
        orderReceiveLoad.setDepartmentId(departmentId);
        orderReceiveLoad.setChannelCode(channelCode);
        orderReceiveLoadService.save(orderReceiveLoad);
        cellInventoryInout.setReceiveLoadId(orderReceiveLoad.getId());
        cellInventoryInout.setEnterpriseCode(enterpriseCode);
        cellInventoryInout.setBusinessType(CellInventoryInout.BusinessType.inByLoad);
        cellInventoryInout.setRemark(CellInventoryInout.BusinessType.inByLoad.getDesc());
        cellInventoryInout.setTotal(getTotal(cellInventoryInoutForm.getDetailList()));
        cellInventoryInout.setChannelCode(channelCode);
        cellInventoryInout.setRoleId(roleId);
        inventoryInoutService.save(cellInventoryInout);
        saveDetail(cellInventoryInoutForm.getDetailList(),cellInventoryInout.getId(),CellInventoryInout.Type.in.name());
        //异步同步数据
        cellInventoryInout.setEnterpriseCode(enterpriseCode);
        sendMsg(cellInventoryInout,cellInventoryInoutForm);
    }

    @Override
    @Transactional
    public void inventoryIn4Simple(OrderReceiveLoadForm orderReceiveLoadForm) {
        //setDefaultValFromDb(orderReceiveLoadForm);
        //if (orderReceiveLoadForm.getQuantityPackUnit()==null){
        //    orderReceiveLoadForm.setQuantityPackUnit(1);
        //}
        if(null == orderReceiveLoadForm.getPackId() || orderReceiveLoadForm.getPackId().equals(0)){
            throw new BusinessException("上货异常:产品["+orderReceiveLoadForm.getSkuCode()+"],没有包装方式参数");
        }
        ProductPackVO productPackVO =productPackService.get4appById(orderReceiveLoadForm.getPackId());
        if(null == productPackVO) {
            throw new BusinessException("上货异常:产品["+orderReceiveLoadForm.getSkuCode()+"],包装方式记录不存在");
        }
        orderReceiveLoadForm.setPackId(productPackVO.getId());
        orderReceiveLoadForm.setPackName(productPackVO.getName());
        orderReceiveLoadForm.setUnitName(productPackVO.getPackUnitName());
        orderReceiveLoadForm.setQuantityPackUnit(productPackVO.getBaseRate());

        List<OrderReceiveLoadDetailForm> detailList=new ArrayList<>();
        OrderReceiveLoadDetailForm orderReceiveLoadDetailForm=new OrderReceiveLoadDetailForm();
        BeanUtils.copyProperties(orderReceiveLoadForm,orderReceiveLoadDetailForm);
        orderReceiveLoadDetailForm.setCabCode(orderReceiveLoadForm.getCabCode());
        orderReceiveLoadDetailForm.setSkuCode(orderReceiveLoadForm.getSkuCode());
        orderReceiveLoadDetailForm.setSpaceCode(orderReceiveLoadForm.getSpaceCode());
        orderReceiveLoadDetailForm.setQuantity(orderReceiveLoadForm.getQuantity());
        orderReceiveLoadDetailForm.setQuantityPackUnit(orderReceiveLoadForm.getQuantityPackUnit());
        orderReceiveLoadDetailForm.setPackId(orderReceiveLoadForm.getPackId());
        orderReceiveLoadDetailForm.setPackName(orderReceiveLoadForm.getPackName());
        orderReceiveLoadDetailForm.setUnitName(orderReceiveLoadForm.getUnitName());
        orderReceiveLoadDetailForm.setQuantityPack(orderReceiveLoadForm.getQuantity()*orderReceiveLoadForm.getQuantityPackUnit());
        detailList.add(orderReceiveLoadDetailForm);
        orderReceiveLoadForm.setDetailList(detailList);
        this.inventoryIn4BatchSimple(orderReceiveLoadForm);
    }

    @Override
    @Transactional
    public void inventoryIn4BatchSimple(OrderReceiveLoadForm orderReceiveLoadForm) {
        //setDefaultVal(orderReceiveLoadForm);
        SystemRuleInfo systemRuleInfo=systemRuleInfoService.getOne(new QueryWrapper<SystemRuleInfo>());
        boolean warehouseInventoryFlag=false;
        if (systemRuleInfo!=null){
            warehouseInventoryFlag=systemRuleInfo.getWarehouseInventoryFlag();
        }
        Long enterpriseId=JwtUtils.getEnterpriseId();
        String enterpriseCode=JwtUtils.getEnterpriseCode();
        Long departmentId=JwtUtils.getDepartmentId();
        String departmentName=JwtUtils.getDepartmentName();
        String roleName=JwtUtils.getRoleName();
        String channelCode=JwtUtils.getChannelCode();
        Long roleId=JwtUtils.getRoleId();

        if (CollectionUtil.isEmpty(orderReceiveLoadForm.getDetailList())){
            throw new BusinessException("缺少上货明细参数");
        }

        CellInventoryInoutForm cellInventoryInoutForm=new CellInventoryInoutForm();
//        cellInventoryInoutForm.setReceiveLoadId(orderReceiveLoad.getId());
        List<CellInventoryInoutDetailForm> detailList=new ArrayList<>();
//        CellInventoryInoutDetailForm cellInventoryInoutDetailForm=new CellInventoryInoutDetailForm();
//        cellInventoryInoutDetailForm.setCabCode(orderReceiveLoadForm.getCabCode());
//        cellInventoryInoutDetailForm.setSkuCode(orderReceiveLoadForm.getSkuCode());
//        cellInventoryInoutDetailForm.setSpaceCode(orderReceiveLoadForm.getSpaceCode());
//        cellInventoryInoutDetailForm.setQuantity(orderReceiveLoadForm.getQuantity());
//
//        detailList.add(cellInventoryInoutDetailForm);
        for(OrderReceiveLoadDetailForm orderReceiveLoadDetailForm:orderReceiveLoadForm.getDetailList()){
            CellInventoryInoutDetailForm cellInventoryInoutDetailForm=new CellInventoryInoutDetailForm();
            cellInventoryInoutDetailForm.setCabCode(orderReceiveLoadDetailForm.getCabCode());
            cellInventoryInoutDetailForm.setSkuCode(orderReceiveLoadDetailForm.getSkuCode());
            cellInventoryInoutDetailForm.setSpaceCode(orderReceiveLoadDetailForm.getSpaceCode());
            cellInventoryInoutDetailForm.setQuantity(orderReceiveLoadDetailForm.getQuantity());
            cellInventoryInoutDetailForm.setQuantityPackUnit(orderReceiveLoadDetailForm.getQuantityPackUnit());
            cellInventoryInoutDetailForm.setPackId(orderReceiveLoadDetailForm.getPackId());
            cellInventoryInoutDetailForm.setPackName(orderReceiveLoadDetailForm.getPackName());
            cellInventoryInoutDetailForm.setUnitName(orderReceiveLoadDetailForm.getUnitName());
            orderReceiveLoadDetailForm.setQuantityPack(orderReceiveLoadDetailForm.getQuantity()*orderReceiveLoadDetailForm.getQuantityPackUnit());
            detailList.add(cellInventoryInoutDetailForm);
        }
        cellInventoryInoutForm.setDetailList(detailList);
        if (warehouseInventoryFlag){
            cabInventoryProductService.checkWarehouseInventory4Load(cellInventoryInoutForm.getDetailList());
        }


        Long creator=JwtUtils.getLoginUserId();
        String creatorName=JwtUtils.getLoginUsername();

        CellInventoryInout cellInventoryInout=new CellInventoryInout();
        BeanUtils.copyProperties(cellInventoryInoutForm,cellInventoryInout);
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMdd");

        String code=dynamicService.getDayNextCode("cab_cell_inventory_inout");
        String day=simpleDateFormat.format(new Date());
        cellInventoryInout.setCode("INS-"+day+"-"+code);
        cellInventoryInout.setDay(Integer.valueOf(day));
        cellInventoryInout.setNo(Integer.valueOf(code));
        cellInventoryInout.setCreator(creator);
        cellInventoryInout.setCreatorName(creatorName);
        cellInventoryInout.setType(CellInventoryInout.Type.in);
        cellInventoryInout.setDepartmentId(departmentId);
        cellInventoryInout.setDepartmentName(departmentName);
        cellInventoryInoutForm.setCreator(creator);
        cellInventoryInoutForm.setCreatorName(creatorName);
//        saveReceiveLoad(cellInventoryInoutForm);

        OrderReceiveLoad orderReceiveLoad=new OrderReceiveLoad();
        BeanUtils.copyProperties(orderReceiveLoadForm,orderReceiveLoad);
//        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMdd");
        code=dynamicService.getDayNextCode("ord_order_receive_load");
//        String day=simpleDateFormat.format(new Date());
        orderReceiveLoad.setCode("RLS-"+day+"-"+code);
        orderReceiveLoad.setDay(Integer.valueOf(day));
        orderReceiveLoad.setNo(Integer.valueOf(code));
        orderReceiveLoad.setCreator(JwtUtils.getLoginUserId());
        orderReceiveLoad.setCreatorName(JwtUtils.getLoginUsername());
        orderReceiveLoad.setEnterpriseCode(enterpriseCode);
        orderReceiveLoad.setDepartmentName(departmentName);
        orderReceiveLoad.setRoleName(roleName);
        orderReceiveLoad.setDepartmentId(departmentId);
        orderReceiveLoad.setChannelCode(channelCode);
        orderReceiveLoad.setRoleId(roleId);

        orderReceiveLoadService.save(orderReceiveLoad);
        saveReceiveLoadDetail(orderReceiveLoadForm,orderReceiveLoad.getId());
        cellInventoryInout.setReceiveLoadId(orderReceiveLoad.getId());
        cellInventoryInout.setEnterpriseCode(enterpriseCode);
        cellInventoryInout.setBusinessType(CellInventoryInout.BusinessType.inByLoad);
        cellInventoryInout.setRemark(CellInventoryInout.BusinessType.inByLoad.getDesc());
        cellInventoryInout.setTotal(getTotal(cellInventoryInoutForm.getDetailList()));
        cellInventoryInout.setDepartmentName(departmentName);
        cellInventoryInout.setRoleName(roleName);
        cellInventoryInout.setChannelCode(channelCode);
        cellInventoryInout.setRoleId(roleId);
        inventoryInoutService.save(cellInventoryInout);
        saveDetail(cellInventoryInoutForm.getDetailList(),cellInventoryInout.getId(),CellInventoryInout.Type.in.name());

        //异步同步数据
        cellInventoryInout.setEnterpriseCode(enterpriseCode);
        sendMsg(cellInventoryInout,cellInventoryInoutForm);
    }

    void sendMsg(CellInventoryInout cellInventoryInout,CellInventoryInoutForm cellInventoryInoutForm){
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
            @Override
            public void afterCommit() {
                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        try{
                            syncInventory(cellInventoryInout,cellInventoryInoutForm.getDetailList());
                        }catch (Exception e){
                            log.error("syn fail",e);
                        }

                    }
                });
            }
        });
    }



    @Override
    @Transactional
    public void inventoryIn(List<CellInventoryInoutForm> cellInventoryInoutFormList) {
        for (CellInventoryInoutForm cellInventoryInoutForm:cellInventoryInoutFormList){
            inventoryIn(cellInventoryInoutForm);
        }
    }

    void saveReceiveLoad(CellInventoryInoutForm cellInventoryInoutForm){

        Long receiveId=cellInventoryInoutForm.getReceiveId();
        if (CollectionUtils.isNotEmpty(cellInventoryInoutForm.getDetailList())){
            for (CellInventoryInoutDetailForm cellInventoryInoutDetailForm:cellInventoryInoutForm.getDetailList()){
                OrderReceiveDetailVO receiveDetailVO=receiveDetailService.get4appById(cellInventoryInoutDetailForm.getReceiveDetailId());
                if (receiveDetailVO!=null){
                    Integer quantityLoad=receiveDetailVO.getQuantityLoad();
                    Integer quantityReceive=receiveDetailVO.getQuantityReceive();
                    if (quantityLoad==null){
                        quantityLoad=0;
                    }
                    if (quantityReceive==null){
                        quantityReceive=0;
                    }
                    if ((quantityLoad+cellInventoryInoutDetailForm.getQuantity())>quantityReceive){
                        throw new BusinessException("上货数量不能大于领货数量");
                    }
                    if(Integer.valueOf(quantityLoad+cellInventoryInoutDetailForm.getQuantity()).intValue()==receiveDetailVO.getQuantityReceive().intValue()){
                        OrderReceiveDetail updateReceiveDetail=new OrderReceiveDetail();
                        updateReceiveDetail.setId(receiveDetailVO.getId());
                        updateReceiveDetail.setStatus(OrderReceiveDetail.Status.finish);
                        receiveDetailService.updateById(updateReceiveDetail);
                    }else{
                        if (OrderReceiveDetail.Status.created.equals(receiveDetailVO.getStatus())){
                            OrderReceiveDetail updateReceiveDetail=new OrderReceiveDetail();
                            updateReceiveDetail.setId(receiveDetailVO.getId());
                            updateReceiveDetail.setStatus(OrderReceiveDetail.Status.loading);
                            receiveDetailService.updateById(updateReceiveDetail);
                        }
                    }

                    Long receiveDetailId=cellInventoryInoutDetailForm.getReceiveDetailId();
                    /**
                     OrderReceiveLoad receiveLoad=new OrderReceiveLoad();
                     receiveLoad.setReceiveId(receiveId);
                     receiveLoad.setReceiveDetailId(receiveDetailId);
                     receiveLoad.setQuantity(cellInventoryInoutDetailForm.getQuantity());
                     receiveLoad.setCreator(cellInventoryInoutForm.getCreator());
                     receiveLoad.setCreatorName(cellInventoryInoutForm.getCreatorName());
                     receiveLoad.setCabCode(cellInventoryInoutDetailForm.getCabCode());
                     receiveLoad.setSpaceCode(cellInventoryInoutDetailForm.getSpaceCode());
                     receiveLoad.setSkuCode(cellInventoryInoutDetailForm.getSkuCode());
                     receiveLoadService.save(receiveLoad);
                     */
                }
            }
            int count=receiveDetailService.countNotFinish(cellInventoryInoutForm.getReceiveId());
            if (count==0){
                OrderReceive orderReceive=new OrderReceive();
                orderReceive.setId(cellInventoryInoutForm.getReceiveId());
                orderReceive.setStatus(OrderReceive.Status.finish);
                receiveService.updateById(orderReceive);
            }else{
                OrderReceive orderReceive=new OrderReceive();
                orderReceive.setId(cellInventoryInoutForm.getReceiveId());
                orderReceive.setStatus(OrderReceive.Status.loading);
                receiveService.updateById(orderReceive);
            }
        }

    }

    void saveDeliverLoad(CellInventoryInoutForm cellInventoryInoutForm){
        Long deliverId=cellInventoryInoutForm.getDeliveryId();
        if (CollectionUtils.isNotEmpty(cellInventoryInoutForm.getDetailList())){
            for (CellInventoryInoutDetailForm cellInventoryInoutDetailForm:cellInventoryInoutForm.getDetailList()){
                OrderDeliveryDetailVO deliveryDetailVO=deliveryDetailService.get4appById(cellInventoryInoutDetailForm.getDetailId());
                if (deliveryDetailVO!=null){
                    Integer quantityLoad=deliveryDetailVO.getQuantityLoad();
                    if (quantityLoad==null){
                        quantityLoad=0;
                    }
                    if ((quantityLoad+cellInventoryInoutDetailForm.getQuantity())>deliveryDetailVO.getQuantityReceive()){
                        throw new BusinessException("上货数量不能大于配送数量");
                    }else if(Integer.valueOf(quantityLoad+cellInventoryInoutDetailForm.getQuantity()).intValue()==deliveryDetailVO.getQuantityReceive().intValue()){
                        OrderDeliveryDetail updateDeliverDetail=new OrderDeliveryDetail();
                        updateDeliverDetail.setId(deliveryDetailVO.getId());
                        updateDeliverDetail.setStatus(OrderDeliveryDetail.Status.finish);
                        deliveryDetailService.updateById(updateDeliverDetail);
                    }
                    Long deliverDetailId=cellInventoryInoutDetailForm.getDetailId();
                    OrderDeliveryLoad deliveryLoad=new OrderDeliveryLoad();
                    deliveryLoad.setDeliveryId(deliverId);
                    deliveryLoad.setDeliveryDetailId(deliverDetailId);
                    deliveryLoad.setQuantity(cellInventoryInoutDetailForm.getQuantity());
                    deliveryLoadService.save(deliveryLoad);
                }
            }
        }
    }

    @Override
    public JsonResult isInventoryIn(CellInventoryInoutDetailForm cellInventoryInoutDetailForm) {
        List<CabinetCargoLane> lanes=laneService.list(new QueryWrapper<CabinetCargoLane>().eq("cab_code",cellInventoryInoutDetailForm.getCabCode()).eq("code",cellInventoryInoutDetailForm.getSpaceCode()));
        if (lanes.size()==0){
            return JsonResult.fail("未找到货道");
        }
        List<CellInventorySpace> spaceInventoryList=cellInventorySpaceService.list(new QueryWrapper<CellInventorySpace>().eq("cab_code",cellInventoryInoutDetailForm.getCabCode()).eq("space_code",cellInventoryInoutDetailForm.getSpaceCode()));
        if (spaceInventoryList.size()>0){
            if (spaceInventoryList.get(0).getQuantity()!=null&&spaceInventoryList.get(0).getQuantity()>0&&!spaceInventoryList.get(0).getSkuCode().equals(cellInventoryInoutDetailForm.getSkuCode())){
                return JsonResult.fail("此货位已经存放了SKU编码:["+spaceInventoryList.get(0).getSkuCode()+"]的刀具,"+"不可以在存放SKU编码:["+cellInventoryInoutDetailForm.getSkuCode()+"]的刀具");
            }
            log.info("pack unit:{}",cellInventoryInoutDetailForm.getQuantityPackUnit().equals(spaceInventoryList.get(0).getQuantityPackUnit()));
            log.info("");
            if (spaceInventoryList.get(0).getQuantity()!=null&&spaceInventoryList.get(0).getQuantity()>0&&spaceInventoryList.get(0).getSkuCode().equals(cellInventoryInoutDetailForm.getSkuCode())&&
                    (cellInventoryInoutDetailForm.getQuantityPackUnit()!=null&&!cellInventoryInoutDetailForm.getQuantityPackUnit().equals(spaceInventoryList.get(0).getQuantityPackUnit()))){
                return JsonResult.fail("此货位已经存放了SKU编码:["+spaceInventoryList.get(0).getSkuCode()+"],包装规格数量:["+spaceInventoryList.get(0).getQuantityPackUnit()+"]的刀具,"+"不可以在存放包装规格数量:["+cellInventoryInoutDetailForm.getQuantityPackUnit()+"]的刀具");
            }
            Integer laneQuantity=lanes.get(0).getQuantity();
            Integer inventoryQuantity=spaceInventoryList.get(0).getQuantity();
            Integer surplusQuantity=laneQuantity-inventoryQuantity;
            if (surplusQuantity.intValue()<cellInventoryInoutDetailForm.getQuantity().intValue()){
                return JsonResult.fail("此货道剩余可上货数不够");
            }
        }
        return JsonResult.success();
    }

    @Transactional
    void saveDetail(List<CellInventoryInoutDetailForm> list,Long inventoryInoutId,String inOutTypeName){
        List<Cabinet> cabinets=cabinetService.list(new QueryWrapper<Cabinet>().eq("code",list.get(0).getCabCode()));
        String mainCabCode=null;
        if (cabinets.size()>0){
            mainCabCode=cabinets.get(0).getBelongCabinet();
        }
        Long enterpriseId=JwtUtils.getEnterpriseId();
        Long creator=JwtUtils.getLoginUserId();
        String creatorName=JwtUtils.getLoginUsername();
        String enterpriseCode=JwtUtils.getEnterpriseCode();
        String channelCode=JwtUtils.getChannelCode();
        if (CollectionUtils.isNotEmpty(list)){
            for (CellInventoryInoutDetailForm cellInventoryInoutDetailForm:list){
                if (cellInventoryInoutDetailForm.getQuantityPackUnit()==null){
                    cellInventoryInoutDetailForm.setQuantityPackUnit(1);
                }
                CellInventoryInoutDetail cellInventoryInoutDetail=new CellInventoryInoutDetail();
                BeanUtils.copyProperties(cellInventoryInoutDetailForm,cellInventoryInoutDetail);
                cellInventoryInoutDetail.setId(null);
                cellInventoryInoutDetail.setCreator(creator);
                cellInventoryInoutDetail.setCreatorName(creatorName);
                cellInventoryInoutDetail.setEnterpriseCode(enterpriseCode);
                cellInventoryInoutDetail.setCompanyId(enterpriseId);
                cellInventoryInoutDetail.setType(CellInventoryInoutDetail.Type.jsonCreator(inOutTypeName));
                cellInventoryInoutDetail.setInoutId(inventoryInoutId);
                cellInventoryInoutDetail.setMainCabCode(mainCabCode);
                cellInventoryInoutDetailForm.setMainCabCode(cellInventoryInoutDetail.getMainCabCode());
                Long packId=cellInventoryInoutDetailForm.getPackId();
                QueryWrapper productQueryWrapper = new QueryWrapper();
                productQueryWrapper.eq("sku_code", cellInventoryInoutDetailForm.getSkuCode());
                ProductDetail productDetail = productDetailService.getOne(productQueryWrapper);
                //List<ProductDetail> productDetails = productDetailService.listBySkuCode(cellInventoryInoutDetailForm.getSkuCode());

                Integer quantityPack=null;
                Integer quantityPackUnit=null;

                List<CellInventorySpace> spaceInventoryList=cellInventorySpaceService.list(new QueryWrapper<CellInventorySpace>().eq("cab_code",cellInventoryInoutDetailForm.getCabCode()).eq("space_code",cellInventoryInoutDetailForm.getSpaceCode()));
                if ((CellInventoryInout.Type.out.name().equals(inOutTypeName)||CellInventoryInout.Type.unload.name().equals(inOutTypeName))&&spaceInventoryList.size()>0){
                    cellInventoryInoutDetailForm.setQuantityPackUnit(spaceInventoryList.get(0).getQuantityPackUnit());
                }
                List<CellInventorySpace> spaceSkuList=cellInventorySpaceService.list(new QueryWrapper<CellInventorySpace>().eq("cab_code",cellInventoryInoutDetailForm.getCabCode()).eq("space_code",cellInventoryInoutDetailForm.getSpaceCode()).eq("sku_code",cellInventoryInoutDetailForm.getSkuCode()).eq("quantity_pack_unit",cellInventoryInoutDetailForm.getQuantityPackUnit()));
                List<CellSingleInventoryProduct> skuSingleInventoryList=cellSingleInventoryProductService.list(new QueryWrapper<CellSingleInventoryProduct>().eq("cab_code",cellInventoryInoutDetailForm.getCabCode()).eq("sku_code",cellInventoryInoutDetailForm.getSkuCode()).eq("quantity_pack_unit",cellInventoryInoutDetailForm.getQuantityPackUnit()));
                List<CellInventoryProduct> skuInventoryList=cellInventoryProductService.list(new QueryWrapper<CellInventoryProduct>().eq("sku_code",cellInventoryInoutDetailForm.getSkuCode()).eq("enterprise_code",enterpriseCode).eq("quantity_pack_unit",cellInventoryInoutDetailForm.getQuantityPackUnit()));
                if (CellInventoryInout.Type.out.name().equals(inOutTypeName)||CellInventoryInout.Type.unload.name().equals(inOutTypeName)){
                    if (spaceSkuList.size()==0){
                        throw new BusinessException("未找到柜子编号["+cellInventoryInoutDetailForm.getCabCode()+"],货道编号["+cellInventoryInoutDetailForm.getSpaceCode()+"]上的刀具产品");
                    }else{
                        if (spaceInventoryList.get(0).getQuantityPackUnit()!=null){
                            cellInventoryInoutDetailForm.setQuantityPackUnit(spaceInventoryList.get(0).getQuantityPackUnit());
                        }

                        quantityPack=cellInventoryInoutDetailForm.getQuantityPackUnit()*cellInventoryInoutDetailForm.getQuantity();
                        quantityPackUnit=cellInventoryInoutDetailForm.getQuantityPackUnit();
//                        packId=spaceInventoryList.get(0).getPackId();


                        cellInventoryInoutDetail.setPackName(spaceInventoryList.get(0).getPackName());
                        cellInventoryInoutDetail.setPackId(spaceInventoryList.get(0).getPackId());
                        cellInventoryInoutDetail.setUnitName(spaceInventoryList.get(0).getUnitName());
                        cellInventoryInoutDetailForm.setQuantityPack(quantityPack);
                        cellInventoryInoutDetailForm.setQuantityPackUnit(cellInventoryInoutDetail.getQuantityPackUnit());
                        cellInventoryInoutDetailForm.setPackName(cellInventoryInoutDetail.getPackName());
                        cellInventoryInoutDetailForm.setPackId(cellInventoryInoutDetail.getPackId());
                        cellInventoryInoutDetailForm.setUnitName(cellInventoryInoutDetail.getUnitName());

                        cellInventoryInoutDetailForm.setSkuCode(spaceSkuList.get(0).getSkuCode());
                        Integer quantity=cellInventoryInoutDetailForm.getQuantity();
                        if (quantity<=0){
                            throw new BusinessException("领取数量参数异常");
                        }
                        if (quantity>0){
                            quantity=-1*quantity;
                        }
                        if (quantityPack>0){
                            quantityPack=-1*quantityPack;
                        }

                        Integer currentQuantity=spaceSkuList.get(0).getQuantity();
                        Integer newQuantity=currentQuantity+quantity;
                        if (newQuantity<0){
                            throw new BusinessException("柜子编号["+cellInventoryInoutDetailForm.getCabCode()+"],货道编号["+cellInventoryInoutDetailForm.getSpaceCode()+"]上的刀具产品库存不足");
                        }
                        CellInventorySpace cellInventorySpace=new CellInventorySpace();
                        cellInventorySpace.setId(spaceSkuList.get(0).getId());
                        cellInventorySpace.setQuantity(newQuantity);
//                        if (quantityPack!=null){
                        Integer currentQuantityPack=spaceInventoryList.get(0).getQuantityPack();
                        if (currentQuantityPack==null){
                            currentQuantityPack=0;
                        }
                        cellInventorySpace.setQuantityPack(currentQuantityPack+quantityPack);
//                            cellInventorySpace.setQuantityPackUnit(quantityPackUnit);
//                        }
//                        cellInventorySpace.setPackId(packId);
                        cellInventorySpace.setMainCabCode(mainCabCode);
                        if (newQuantity<=0){
//                            cellInventorySpaceService.removeById(spaceSkuList.get(0).getId());
                            cellInventorySpace.setQuantity(0);
                            cellInventorySpace.setQuantityPack(0);
                        }
//                        else{
                        cellInventorySpaceService.updateById(cellInventorySpace);
//                        }
                        cellInventoryInoutDetail.setQuantityPackCurrent(currentQuantityPack);
                        cellInventoryInoutDetail.setQuantityPackAfter(currentQuantityPack+quantityPack);

                        if(skuSingleInventoryList.size()>0){
                            CellSingleInventoryProduct cellSingleInventoryProduct=new CellSingleInventoryProduct();
                            cellSingleInventoryProduct.setId(skuSingleInventoryList.get(0).getId());
                            cellSingleInventoryProduct.setCabCode(cellInventoryInoutDetailForm.getCabCode());
                            cellSingleInventoryProduct.setSkuCode(cellInventoryInoutDetailForm.getSkuCode());
                            cellSingleInventoryProduct.setQuantity(skuSingleInventoryList.get(0).getQuantity()+quantity);
                            cellSingleInventoryProduct.setMainCabCode(mainCabCode);
//                            cellSingleInventoryProduct.setPackId(packId);

                            cellInventoryInoutDetail.setQuantitySingleCabCurrent(skuSingleInventoryList.get(0).getQuantity());
                            cellInventoryInoutDetail.setQuantitySingleCabAfter(cellSingleInventoryProduct.getQuantity());

//                            if (quantityPack!=null){
                            currentQuantityPack=skuSingleInventoryList.get(0).getQuantityPack();
                            if (currentQuantityPack==null){
                                currentQuantityPack=0;
                            }
                            cellSingleInventoryProduct.setQuantityPack(currentQuantityPack+quantityPack);
//                                cellSingleInventoryProduct.setQuantityPackUnit(quantityPackUnit);
//                            }
                            cellInventoryInoutDetail.setQuantityPackSingleCabCurrent(currentQuantityPack);
                            cellInventoryInoutDetail.setQuantityPackSingleCabAfter(cellSingleInventoryProduct.getQuantityPack());
                            if (cellSingleInventoryProduct.getQuantity()<=0){
//                                cellSingleInventoryProductService.removeById(skuSingleInventoryList.get(0).getId());
                                cellSingleInventoryProduct.setQuantity(0);
                                cellSingleInventoryProduct.setQuantityPack(0);
                            }

//                            else{
                            cellSingleInventoryProductService.updateById(cellSingleInventoryProduct);
//                            }
                        }

                        if(skuInventoryList.size()>0){
                            CellInventoryProduct cellInventoryProduct=new CellInventoryProduct();
                            cellInventoryProduct.setId(skuInventoryList.get(0).getId());
                            cellInventoryProduct.setSkuCode(cellInventoryInoutDetailForm.getSkuCode());
                            cellInventoryProduct.setQuantity(skuInventoryList.get(0).getQuantity()+quantity);
//                            if (quantityPack!=null){
                            currentQuantityPack=skuInventoryList.get(0).getQuantityPack();
                            if (currentQuantityPack==null){
                                currentQuantityPack=0;
                            }
                            cellInventoryProduct.setQuantityPack(currentQuantityPack+quantityPack);
//                                cellInventoryProduct.setQuantityPackUnit(quantityPackUnit);
//                            }
//                            cellInventoryProduct.setPackId(packId);

                            cellInventoryInoutDetail.setQuantityCabCurrent(skuInventoryList.get(0).getQuantity());
                            cellInventoryInoutDetail.setQuantityCabAfter(cellInventoryProduct.getQuantity());

                            cellInventoryInoutDetail.setQuantityPackCabCurrent(currentQuantityPack);
                            cellInventoryInoutDetail.setQuantityPackCabAfter(cellInventoryProduct.getQuantityPack());
                            if (cellInventoryProduct.getQuantity()<=0){
//                                cellInventoryProductService.removeById(skuInventoryList.get(0).getId());
                                cellInventoryProduct.setQuantity(0);
                                cellInventoryProduct.setQuantityPack(0);
                            }
//                            else{
                            cellInventoryProductService.updateById(cellInventoryProduct);
//                            }
                        }

                        cellInventoryInoutDetail.setQuantityCurrent(currentQuantity);
                        cellInventoryInoutDetail.setQuantityAfter(newQuantity);
                        cellInventoryInoutDetail.setQuantity(quantity);
                        cellInventoryInoutDetail.setMainCabCode(mainCabCode);
                        cellInventoryInoutDetail.setChannelCode(channelCode);


//                        List<ProductDetail> productDetails = productDetailService.list(new QueryWrapper<ProductDetail>().eq("sku_code", cellInventoryInoutDetailForm.getSkuCode()));
//                        if (productDetails.size() > 0) {
//                            if (productDetails.get(0).getLifeSpan() != null) {
//                                cellInventoryInoutDetail.setRemainingTime(productDetails.get(0).getLifeSpan());
//                                cellInventoryInoutDetail.setSettingTime(productDetails.get(0).getLifeSpan());
//                            }
//
//                            if (productDetails.get(0).getLifeUnit() != null) {
//                                cellInventoryInoutDetail.setLifeUnit(CellInventoryInoutDetail.LifeUnit.jsonCreator(productDetails.get(0).getLifeUnit().name()));
//                            }
//
//                        }
                        if(null != productDetail){
                            if (productDetail.getLifeSpan() != null) {
                                cellInventoryInoutDetail.setRemainingTime(productDetail.getLifeSpan());
                                cellInventoryInoutDetail.setSettingTime(productDetail.getLifeSpan());
                            }

                            if (productDetail.getLifeUnit() != null) {
                                cellInventoryInoutDetail.setLifeUnit(CellInventoryInoutDetail.LifeUnit.jsonCreator(productDetail.getLifeUnit().name()));
                            }
                        }
//                        baseMapper.insert(cellInventoryInoutDetail);
                    }
                }else if(CellInventoryInout.Type.in.name().equals(inOutTypeName)){


                    quantityPack=cellInventoryInoutDetailForm.getQuantityPackUnit()*cellInventoryInoutDetailForm.getQuantity();
                    quantityPackUnit=cellInventoryInoutDetailForm.getQuantityPackUnit();
                    cellInventoryInoutDetailForm.setQuantityPack(quantityPack);

                    JsonResult usableResult=isInventoryIn(cellInventoryInoutDetailForm);
                    if (JsonResult.Code.SUCCESS.getCode()!=usableResult.getCode()){
                        throw new BusinessException(usableResult.getMsg());
                    }
                    Integer quantity=cellInventoryInoutDetailForm.getQuantity();
                    if (quantity<=0){
                        throw new BusinessException("上货数量参数异常");
                    }
                    //修改库存表(按货道)
                    if (spaceInventoryList.size()==0){
                        CellInventorySpace cellInventorySpace=new CellInventorySpace();
                        cellInventorySpace.setQuantity(quantity);
                        cellInventorySpace.setCabCode(cellInventoryInoutDetailForm.getCabCode());
                        cellInventorySpace.setSkuCode(cellInventoryInoutDetailForm.getSkuCode());
                        cellInventorySpace.setSpaceCode(cellInventoryInoutDetailForm.getSpaceCode());
                        cellInventorySpace.setQuantity(quantity);
                        cellInventorySpace.setCompanyId(enterpriseId);
                        cellInventorySpace.setEnterpriseCode(enterpriseCode);
                        cellInventorySpace.setChannelCode(channelCode);
                        cellInventorySpace.setMainCabCode(mainCabCode);
                        cellInventorySpace.setQuantityPackUnit(quantityPackUnit);
                        cellInventorySpace.setQuantityPack(quantityPack);
                        cellInventorySpace.setPackId(cellInventoryInoutDetailForm.getPackId());
                        cellInventorySpace.setPackName(cellInventoryInoutDetailForm.getPackName());
                        cellInventorySpace.setUnitName(cellInventoryInoutDetailForm.getUnitName());
                        cellInventorySpaceService.save(cellInventorySpace);

                        cellInventoryInoutDetail.setQuantityCurrent(0);
                        cellInventoryInoutDetail.setQuantityAfter(quantity);
                        cellInventoryInoutDetail.setQuantity(quantity);
                        cellInventoryInoutDetail.setQuantityPackCurrent(0);
                        cellInventoryInoutDetail.setQuantityPackAfter(quantityPack);
//                        baseMapper.insert(cellInventoryInoutDetail);
                    }else{
                        Integer currentQuantity=spaceInventoryList.get(0).getQuantity();
                        Integer newQuantity=currentQuantity+quantity;

                        CellInventorySpace cellInventorySpace=new CellInventorySpace();
                        cellInventorySpace.setId(spaceInventoryList.get(0).getId());
                        cellInventorySpace.setQuantity(newQuantity);
                        cellInventorySpace.setPackName(cellInventoryInoutDetailForm.getPackName());
                        cellInventorySpace.setPackId(cellInventoryInoutDetailForm.getPackId());
                        cellInventorySpace.setUnitName(cellInventoryInoutDetailForm.getUnitName());

//                        if (quantityPack!=null){
                        Integer currentQuantityPack=spaceInventoryList.get(0).getQuantityPack();
                        if (currentQuantityPack==null){
                            currentQuantityPack=0;
                        }
                        cellInventorySpace.setQuantityPack(currentQuantityPack+quantityPack);
                        cellInventorySpace.setQuantityPackUnit(quantityPackUnit);
//                        }
                        if (spaceInventoryList.get(0).getQuantity()==0){
                            cellInventorySpace.setSkuCode(cellInventoryInoutDetailForm.getSkuCode());
                        }
                        cellInventorySpace.setMainCabCode(mainCabCode);

                        cellInventorySpaceService.updateById(cellInventorySpace);


                        cellInventoryInoutDetail.setQuantityCurrent(currentQuantity);
                        cellInventoryInoutDetail.setQuantityAfter(newQuantity);
                        cellInventoryInoutDetail.setQuantity(quantity);
                        cellInventoryInoutDetail.setMainCabCode(mainCabCode);
                        cellInventoryInoutDetail.setQuantityPackCurrent(currentQuantityPack);
                        cellInventoryInoutDetail.setQuantityPackAfter(cellInventorySpace.getQuantityPack());
//                        baseMapper.insert(cellInventoryInoutDetail);
                    }
                    //修改库存表(按柜子)
                    if (skuSingleInventoryList.size()==0){
                        CellSingleInventoryProduct cellSingleInventoryProduct=new CellSingleInventoryProduct();
                        cellSingleInventoryProduct.setCabCode(cellInventoryInoutDetailForm.getCabCode());
                        cellSingleInventoryProduct.setSkuCode(cellInventoryInoutDetailForm.getSkuCode());
                        cellSingleInventoryProduct.setQuantity(quantity);
                        cellSingleInventoryProduct.setCompanyId(enterpriseId);
                        cellSingleInventoryProduct.setEnterpriseCode(enterpriseCode);
                        cellSingleInventoryProduct.setChannelCode(channelCode);
                        cellSingleInventoryProduct.setMainCabCode(mainCabCode);
                        cellSingleInventoryProduct.setQuantityPackUnit(quantityPackUnit);
                        cellSingleInventoryProduct.setQuantityPack(quantityPack);
                        cellSingleInventoryProduct.setPackId(packId);
                        cellSingleInventoryProduct.setPackName(cellInventoryInoutDetailForm.getPackName());
                        cellSingleInventoryProduct.setUnitName(cellInventoryInoutDetailForm.getUnitName());
                        cellSingleInventoryProductService.save(cellSingleInventoryProduct);

                        cellInventoryInoutDetail.setQuantitySingleCabCurrent(0);
                        cellInventoryInoutDetail.setQuantitySingleCabAfter(cellSingleInventoryProduct.getQuantity());
                        cellInventoryInoutDetail.setQuantityPackSingleCabCurrent(0);
                        cellInventoryInoutDetail.setQuantityPackSingleCabAfter(cellSingleInventoryProduct.getQuantityPack());
                    }else{
                        CellSingleInventoryProduct cellSingleInventoryProduct=new CellSingleInventoryProduct();
                        cellSingleInventoryProduct.setId(skuSingleInventoryList.get(0).getId());
                        cellSingleInventoryProduct.setCabCode(cellInventoryInoutDetailForm.getCabCode());
                        cellSingleInventoryProduct.setSkuCode(cellInventoryInoutDetailForm.getSkuCode());
                        cellSingleInventoryProduct.setQuantity(skuSingleInventoryList.get(0).getQuantity()+quantity);
                        cellSingleInventoryProduct.setMainCabCode(mainCabCode);
                        cellSingleInventoryProduct.setPackId(packId);
                        cellSingleInventoryProduct.setPackName(cellInventoryInoutDetailForm.getPackName());
                        cellSingleInventoryProduct.setPackId(cellInventoryInoutDetailForm.getPackId());
                        cellSingleInventoryProduct.setUnitName(cellInventoryInoutDetailForm.getUnitName());
//                        if (quantityPack!=null){
                        Integer currentQuantityPack=skuSingleInventoryList.get(0).getQuantityPack();
                        if (currentQuantityPack==null){
                            currentQuantityPack=0;
                        }
                        cellSingleInventoryProduct.setQuantityPack(currentQuantityPack+quantityPack);
                        cellSingleInventoryProduct.setQuantityPackUnit(quantityPackUnit);
//                        }
                        cellSingleInventoryProductService.updateById(cellSingleInventoryProduct);

                        cellInventoryInoutDetail.setQuantitySingleCabCurrent(skuSingleInventoryList.get(0).getQuantity());
                        cellInventoryInoutDetail.setQuantitySingleCabAfter(cellSingleInventoryProduct.getQuantity());
                        cellInventoryInoutDetail.setQuantityPackSingleCabCurrent(currentQuantityPack);
                        cellInventoryInoutDetail.setQuantityPackSingleCabAfter(currentQuantityPack+quantityPack);
                    }

                    //修改库存表(按产品)
                    if (skuInventoryList.size()==0){
                        CellInventoryProduct cellInventoryProduct=new CellInventoryProduct();
                        cellInventoryProduct.setSkuCode(cellInventoryInoutDetailForm.getSkuCode());
                        cellInventoryProduct.setQuantity(quantity);
                        cellInventoryProduct.setCompanyId(enterpriseId);
                        cellInventoryProduct.setEnterpriseCode(enterpriseCode);
                        cellInventoryProduct.setChannelCode(channelCode);
                        cellInventoryProduct.setQuantityPackUnit(quantityPackUnit);
                        cellInventoryProduct.setQuantityPack(quantityPack);
                        cellInventoryProduct.setPackId(packId);
                        cellInventoryProduct.setPackName(cellInventoryInoutDetailForm.getPackName());
                        cellInventoryProduct.setUnitName(cellInventoryInoutDetailForm.getUnitName());
                        cellInventoryProductService.save(cellInventoryProduct);

                        cellInventoryInoutDetail.setQuantityCabCurrent(0);
                        cellInventoryInoutDetail.setQuantityCabAfter(cellInventoryProduct.getQuantity());
                        cellInventoryInoutDetail.setQuantityPackCabCurrent(0);
                        cellInventoryInoutDetail.setQuantityPackCabAfter(quantityPack);
                    }else{
                        CellInventoryProduct cellInventoryProduct=new CellInventoryProduct();
                        cellInventoryProduct.setId(skuInventoryList.get(0).getId());
                        cellInventoryProduct.setSkuCode(cellInventoryInoutDetailForm.getSkuCode());
                        cellInventoryProduct.setQuantity(skuInventoryList.get(0).getQuantity()+quantity);
                        cellInventoryProduct.setPackName(cellInventoryInoutDetailForm.getPackName());
                        cellInventoryProduct.setPackId(cellInventoryInoutDetailForm.getPackId());
                        cellInventoryProduct.setUnitName(cellInventoryInoutDetailForm.getUnitName());
//                        if (quantityPack!=null){
                        Integer currentQuantityPack=skuInventoryList.get(0).getQuantityPack();
                        if (currentQuantityPack==null){
                            currentQuantityPack=0;
                        }
                        cellInventoryProduct.setQuantityPack(currentQuantityPack+quantityPack);
                        cellInventoryProduct.setQuantityPackUnit(quantityPackUnit);
//                        }
                        cellInventoryProduct.setPackId(packId);
                        cellInventoryProductService.updateById(cellInventoryProduct);

                        cellInventoryInoutDetail.setQuantityCabCurrent(skuInventoryList.get(0).getQuantity());
                        cellInventoryInoutDetail.setQuantityCabAfter(cellInventoryProduct.getQuantity());
                        cellInventoryInoutDetail.setQuantityPackCabCurrent(currentQuantityPack);
                        cellInventoryInoutDetail.setQuantityPackCabAfter(currentQuantityPack+quantityPack);
                    }

                    cellInventoryInoutDetail.setMainCabCode(mainCabCode);
                    cellInventoryInoutDetail.setChannelCode(channelCode);

                    //上货时查询产品物料表产品包装条码 是否 存在，不存在，反写
                    //if(null == productDetail.getPackId()){
                    productDetail.setPackId(cellInventoryInoutDetailForm.getPackId());
                    productDetail.setBasePrice(new BigDecimal(1));

                    ProductPack productPack = productPackService.getById(cellInventoryInoutDetailForm.getPackId());
                    if(null != productPack) {
                        productDetail.setUnitId(productPack.getProductUnitId());
                        if(null != productDetail.getMarketPrice()) {
                            productDetail.setBasePrice(productDetail.getMarketPrice().divide(new BigDecimal(productPack.getBaseRate()),2, RoundingMode.HALF_UP));
                        }
                    }
                    productDetailService.updateById(productDetail);
                    //}

                }else{
                    throw new BusinessException("出入库类型参数异常");
                }

                BigDecimal price=null;
                BigDecimal total=null;
//                if (productDetails.size()>0&&productDetails.get(0).getMarketPrice()!=null){
////                    quantityPackUnit=productDetails.get(0).getUnitRate();
////                    if (quantityPackUnit!=null){
////                        quantityPack=cellInventoryInoutDetailForm.getQuantity()*quantityPackUnit;
////                    }
////                    packId=productDetails.get(0).getPackId();
//                    price=productDetails.get(0).getMarketPrice();
//                    if (price!=null){
//                        total=price.multiply(BigDecimal.valueOf(Math.abs(quantityPack)));
//                    }
//                }
                if (null != productDetail && productDetail.getMarketPrice()!=null){
//                    quantityPackUnit=productDetails.get(0).getUnitRate();
//                    if (quantityPackUnit!=null){
//                        quantityPack=cellInventoryInoutDetailForm.getQuantity()*quantityPackUnit;
//                    }
//                    packId=productDetails.get(0).getPackId();
                    price = productDetail.getMarketPrice();
                    if (price!=null){
                        total=price.multiply(BigDecimal.valueOf(Math.abs(cellInventoryInoutDetail.getQuantity())));
                    }
                }
                cellInventoryInoutDetail.setPrice(price);
                cellInventoryInoutDetail.setTotal(total);
                cellInventoryInoutDetail.setQuantityPack(quantityPack);
                cellInventoryInoutDetail.setQuantityPackUnit(quantityPackUnit);
                cellInventoryInoutDetailForm.setPrice(price);
                cellInventoryInoutDetailForm.setTotal(total);
                baseMapper.insert(cellInventoryInoutDetail);
                cellInventoryInoutDetailForm.setStorageInventoryInoutDetailId(cellInventoryInoutDetail.getId());
            }
        }else{
            throw new BusinessException("未提交领用刀具数据");
        }
    }

    public void syncInventory(CellInventoryInout cellInventoryInout,List<CellInventoryInoutDetailForm> list){
        String enterpriseCode = cellInventoryInout.getEnterpriseCode();
//        log.info("param list:{}",JSON.toJSONString(list));
        if (CollectionUtils.isNotEmpty(list)){
//            log.info("enterpriseCode get by runable:{}",enterpriseCode);
            String uniqCode = enterpriseCode+"_"+cellInventoryInout.getId();
            //同步售刀柜上货表
            try {
                cellInventoryInout.setUniqCode(uniqCode);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("type", "addOrUpdate");
                CellInventoryInoutDTO dto = new CellInventoryInoutDTO();
                CopyOptions copyOptions = CopyOptions.create()
                        .setEditable(CellInventoryInout.class)
                        .setIgnoreError(true)
                        .setIgnoreNullValue(true);
                BeanUtil.copyProperties(cellInventoryInout, dto, copyOptions);
                List<CellInventoryInoutDetail> inoutDetails = baseMapper.selectList(new LambdaQueryWrapper<CellInventoryInoutDetail>().eq(CellInventoryInoutDetail::getInoutId,cellInventoryInout.getId()));
                inoutDetails.forEach(s->{
                    s.setSkuCode(enterpriseCode+"_"+s.getSkuCode());
                    s.setInoutUniqCode(uniqCode);
                });
                dto.setDetails(inoutDetails);
                jsonObject.put("data", dto);
                PulsarUtils.send(topicUrl+ PulsarCommons.CELL_INVENTORY_INOUT_TOPIC,jsonObject.toJSONString());
//                log.info("send inout msg:{}",jsonObject.toJSONString());
            }catch (Exception e){
                log.error("sync failed",e);
                CellInventoryInout cellInventory = new CellInventoryInout();
                cellInventory.setId(cellInventoryInout.getId());
                cellInventory.setIsSyns(0);
                inventoryInoutService.updateById(cellInventory);
            }
            //同步售刀柜上货领取明细
            /*CellInventoryInoutDetail inoutDetails = new CellInventoryInoutDetail();
            try {
                inoutDetails = baseMapper.selectOne(new LambdaQueryWrapper<CellInventoryInoutDetail>().eq(CellInventoryInoutDetail::getInoutId,cellInventoryInout.getId()));
                inoutDetails.setInoutUniqCode(uniqCode);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("type", "addOrUpdate");
                jsonObject.put("data", inoutDetails);
                PulsarUtils.send(topicUrl+ PulsarCommons.CELL_INVENTORY_INOUT_DETAIL_TOPIC,jsonObject.toJSONString());
            }catch (Exception e){
                log.error("同步售刀柜上货领取明细失败",e.getMessage());
                CellInventoryInoutDetail cellInventoryInoutDetail = new CellInventoryInoutDetail();
                cellInventoryInoutDetail.setId(inoutDetails.getId());
                cellInventoryInoutDetail.setIsSyns(0);
                baseMapper.updateById(cellInventoryInoutDetail);
            }*/
            List<CellInventoryProduct> inventoryProductList = new ArrayList<>();
            List<CellInventorySpace> inventorySpaceList = new ArrayList<>();
            List<CellSingleInventoryProduct> singleInventoryProductList = new ArrayList<>();
            //同步售刀柜产品库存
            try {
                for(CellInventoryInoutDetailForm item:list){
                    //查询售刀柜产品库存
                    CellInventoryProduct cellInventoryProduct = cellInventoryProductService.getOne(new LambdaQueryWrapper<CellInventoryProduct>().eq(
                            CellInventoryProduct::getSkuCode, item.getSkuCode()));
                    if(cellInventoryProduct!=null){
                        inventoryProductList.add(cellInventoryProduct);
                    }
                    //查询产品货道库存
                    CellInventorySpace cellInventorySpace = cellInventorySpaceService.getOne(new LambdaQueryWrapper<CellInventorySpace>()
                            .eq(CellInventorySpace::getSkuCode, item.getSkuCode())
                            .eq(CellInventorySpace::getCabCode, item.getCabCode())
                            .eq(CellInventorySpace::getSpaceCode, item.getSpaceCode()));
                    if(cellInventorySpace!=null){
                        inventorySpaceList.add(cellInventorySpace);
                    }
                    //查询售刀柜sku库存
                    CellSingleInventoryProduct singleInventoryProduct = cellSingleInventoryProductService.getOne(new LambdaQueryWrapper<CellSingleInventoryProduct>()
                            .eq(CellSingleInventoryProduct::getSkuCode, item.getSkuCode())
                            .eq(CellSingleInventoryProduct::getCabCode, item.getCabCode()));
                    if(singleInventoryProduct!=null){
                        singleInventoryProductList.add(singleInventoryProduct);
                    }
                }
//                log.info("cellInventoryProductList:{}",JSON.toJSONString(inventoryProductList));
//                log.info("cellInventorySpaceList:{}",JSON.toJSONString(inventorySpaceList));
//                log.info("cellSingleInventoryProductList:{}",JSON.toJSONString(singleInventoryProductList));
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("type", "addOrUpdate");
                if(inventoryProductList.size()>0){
                    inventoryProductList.forEach(s->{s.setSkuCode(enterpriseCode+"-"+s.getSkuCode());});
                    JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(inventoryProductList));
                    jsonObject.put("data", jsonArray);
                }else{
                    for(CellInventoryInoutDetailForm item:list){
                        CellInventoryProduct inventoryProduct = new CellInventoryProduct();
                        inventoryProduct.setSkuCode(enterpriseCode+"-"+item.getSkuCode());
                        inventoryProduct.setQuantity(0);
                        inventoryProduct.setEnterpriseCode(enterpriseCode);
                        inventoryProductList.add(inventoryProduct);
                    }
                    JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(inventoryProductList));
                    jsonObject.put("data", jsonArray);
                }
                PulsarUtils.send(topicUrl+ PulsarCommons.CELL_INVENTORY_PRODUCT_TOPIC,jsonObject.toJSONString());
//                log.info("send product inventory msg:{}",jsonObject.toJSONString());
            }catch (Exception e){
                log.error("同步售刀柜产品库存失败",e);
                if(inventoryProductList.size()>0){
                    for(CellInventoryProduct item:inventoryProductList){
                        CellInventoryProduct cellInventoryProduct = new CellInventoryProduct();
                        cellInventoryProduct.setId(item.getId());
                        cellInventoryProduct.setIsSyns(0);
                        cellInventoryProductService.updateById(cellInventoryProduct);
                    }
                }
            }
            //售刀柜产品货道库存
            try {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("type", "addOrUpdate");
                if(inventorySpaceList.size()>0){
                    inventorySpaceList.forEach(s->{s.setSkuCode(enterpriseCode+"-"+s.getSkuCode());});
                    JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(inventorySpaceList));
                    jsonObject.put("data", jsonArray);
                }else {
                    for(CellInventoryInoutDetailForm item:list){
                        CellInventorySpace inventorySpace = new CellInventorySpace();
                        inventorySpace.setSkuCode(enterpriseCode+"-"+item.getSkuCode());
                        inventorySpace.setCabCode(item.getCabCode());
                        inventorySpace.setSpaceCode(item.getSpaceCode());
                        inventorySpace.setQuantity(0);
                        inventorySpace.setEnterpriseCode(enterpriseCode);
                        inventorySpaceList.add(inventorySpace);
                    }
                    JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(inventorySpaceList));
                    jsonObject.put("data", jsonArray);
                }
                PulsarUtils.send(topicUrl+ PulsarCommons.CELL_INVENTORY_SPACE_TOPIC,jsonObject.toJSONString());
//                log.info("send space inventory msg:{}",jsonObject.toJSONString());
            }catch (Exception e){
                log.error("同步售刀柜产品货道库存失败",e);
                if(inventorySpaceList.size()>0){
                    for(CellInventorySpace item:inventorySpaceList){
                        CellInventorySpace cellInventorySpace = new CellInventorySpace();
                        cellInventorySpace.setId(item.getId());
                        cellInventorySpace.setIsSyns(0);
                        cellInventorySpaceService.updateById(cellInventorySpace);
                    }
                }
            }
            //同步售刀柜sku库存
            try {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("type", "addOrUpdate");
                if(singleInventoryProductList.size()>0){
                    singleInventoryProductList.forEach(s->{s.setSkuCode(enterpriseCode+"-"+s.getSkuCode());});
                    JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(singleInventoryProductList));
                    jsonObject.put("data", jsonArray);
                }else {
                    for(CellInventoryInoutDetailForm item:list){
                        CellSingleInventoryProduct singleInventoryProduct = new CellSingleInventoryProduct();
                        singleInventoryProduct.setSkuCode(enterpriseCode+"-"+item.getSkuCode());
                        singleInventoryProduct.setCabCode(item.getCabCode());
                        singleInventoryProduct.setQuantity(0);
                        singleInventoryProduct.setEnterpriseCode(enterpriseCode);
                        singleInventoryProductList.add(singleInventoryProduct);
                    }
                    JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(singleInventoryProductList));
                    jsonObject.put("data", jsonArray);
                }
                PulsarUtils.send(topicUrl+ PulsarCommons.CELL_SINGLE_INVENTORY_PRODUCT_TOPIC,jsonObject.toJSONString());
            }catch (Exception e){
                log.error("同步售刀柜sku库存失败",e);
                if(singleInventoryProductList.size()>0){
                    for(CellSingleInventoryProduct item:singleInventoryProductList){
                        CellSingleInventoryProduct cellSingleInventoryProduct = new CellSingleInventoryProduct();
                        cellSingleInventoryProduct.setId(item.getId());
                        cellSingleInventoryProduct.setIsSyns(0);
                        cellSingleInventoryProductService.updateById(cellSingleInventoryProduct);
                    }
                }
            }
        }
    }

    //未设置定时任务时间
    //@Scheduled(cron = "0/5 * * * * ?")
    public void syncSellKnifeCabTimedTask(){
        //定时同步售刀柜上货
        List<CellInventoryInout> cellInventoryInoutList = inventoryInoutService.list(new LambdaQueryWrapper<CellInventoryInout>()
                .eq(CellInventoryInout::getIsSyns,0));
        if(CollectionUtils.isNotEmpty(cellInventoryInoutList)){
            for(CellInventoryInout inventoryInoutItem:cellInventoryInoutList){
                try{
                    inventoryInoutItem.setUniqCode(BaseDataInit.ENTERPRISE_DATA.getCode()+"-"+inventoryInoutItem.getId());
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("type", "addOrUpdate");
                    jsonObject.put("data", inventoryInoutItem);
                    PulsarUtils.send(topicUrl+ PulsarCommons.CELL_INVENTORY_INOUT_TOPIC,jsonObject.toJSONString());
                }catch (Exception e){
                    log.error("定时同步售刀柜上货失败:"+e.getMessage());
                }
            }
        }
        //定时同步售刀柜上货明细
        List<CellInventoryInoutDetail> inventoryInoutDetailList = baseMapper.selectList(new LambdaQueryWrapper<CellInventoryInoutDetail>()
                .eq(CellInventoryInoutDetail::getIsSyns,0));
        if(CollectionUtils.isNotEmpty(inventoryInoutDetailList)){
            try {
                for(CellInventoryInoutDetail inoutDetailItem:inventoryInoutDetailList){
                    inoutDetailItem.setInoutUniqCode(BaseDataInit.ENTERPRISE_DATA.getCode() + "-" + inoutDetailItem.getInoutId());
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("type", "addOrUpdate");
                    jsonObject.put("data", inoutDetailItem);
                    PulsarUtils.send(topicUrl + PulsarCommons.CELL_INVENTORY_INOUT_DETAIL_TOPIC, jsonObject.toJSONString());
                }
            }catch (Exception e){
                log.error("定时同步售刀柜上货明细失败:"+e.getMessage());
            }
        }
        //定时同步售刀柜产品库存
        List<CellInventoryProduct> inventoryProductListuct = cellInventoryProductService.list(new LambdaQueryWrapper<CellInventoryProduct>()
                .eq(CellInventoryProduct::getIsSyns,0));
        if(CollectionUtils.isNotEmpty(inventoryProductListuct)){
            try {
                for(CellInventoryProduct inventoryProductitem:inventoryProductListuct){
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("type", "addOrUpdate");
                    jsonObject.put("data", inventoryProductitem);
                    PulsarUtils.send(topicUrl+ PulsarCommons.CELL_INVENTORY_PRODUCT_TOPIC,jsonObject.toJSONString());
                }
            }catch (Exception e){
                log.error("定时同步售刀柜产品库存失败:"+e.getMessage());
            }
        }
        //定时同步售刀柜产品货道库存
        List<CellInventorySpace> inventorySpaceList = cellInventorySpaceService.list(new LambdaQueryWrapper<CellInventorySpace>()
                .eq(CellInventorySpace::getIsSyns,0));
        if(CollectionUtils.isNotEmpty(inventorySpaceList)){
            try {
                for(CellInventorySpace inventorySpaceItem:inventorySpaceList){
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("type", "addOrUpdate");
                    jsonObject.put("data", inventorySpaceItem);
                    PulsarUtils.send(topicUrl+ PulsarCommons.CELL_INVENTORY_SPACE_TOPIC,jsonObject.toJSONString());
                }
            }catch (Exception e){
                log.error("定时同步售刀柜产品货道库存失败:"+e.getMessage());
            }
        }
        //定时同步售刀柜sku库存
        List<CellSingleInventoryProduct> singleInventoryProductList = cellSingleInventoryProductService.list(new LambdaQueryWrapper<CellSingleInventoryProduct>()
                .eq(CellSingleInventoryProduct::getIsSyns,0));
        if(CollectionUtils.isNotEmpty(singleInventoryProductList)){
            try {
                for(CellSingleInventoryProduct singleIProductItem:singleInventoryProductList){
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("type", "addOrUpdate");
                    jsonObject.put("data", singleIProductItem);
                    PulsarUtils.send(topicUrl+ PulsarCommons.CELL_SINGLE_INVENTORY_PRODUCT_TOPIC,jsonObject.toJSONString());
                }
            }catch (Exception e){
                log.error("定时同步售刀柜sku库存失败:"+e.getMessage());
            }
        }
    }


    @Transactional
    public void resetTime(AuthorityManage authorityManage){
        //同一个权限组下的所有人的所有的物料 重置更新时间是一样的
        List<CountQuota> countQuotaList1 = countQuotaService.list(new LambdaQueryWrapper<CountQuota>()
                .eq(CountQuota::getAuthorityManageId, authorityManage.getId()));
        if(countQuotaList1.size()>0 && countQuotaList1.get(0).getResetTime() != null){
            LocalDateTime now = LocalDateTime.of(LocalDate.now(), LocalTime.now());
            //如果现在的时间也就是领取时间是在重置更新时间之后，就去将重置更新时间更新为下一次  将剩余可领的金额/数量重置
            if (now.isAfter(countQuotaList1.get(0).getResetTime())){
                //更新统计表
                for (CountQuota countQuota1:countQuotaList1){
                    //额度评估周期
                    if(authorityManage.getLineEvaluatePeriod().equals(AuthorityManage.LineEvaluatePeriod.day)){//每天
                        countQuota1.setResetTime(LocalDateTime.of(LocalDate.now().plusDays(1), LocalTime.MIN));
                        //if (countQuota1.getCreditType().equals(CountQuota.CreditType.money)){
                        countQuota1.setBalance(countQuota1.getLineOfCredit());
                        //}else if(countQuota1.getCreditType(). equals(CountQuota.CreditType.quantity)){
                        countQuota1.setResidualQuantity(countQuota1.getAuthorizedQuantity());
                        //}
                    }else if(authorityManage.getLineEvaluatePeriod().equals(AuthorityManage.LineEvaluatePeriod.week)){//每周
                        countQuota1.setResetTime(LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.next(DayOfWeek.MONDAY)), LocalTime.MIN));
                        //if (countQuota1.getCreditType().equals(CountQuota.CreditType.money)){
                        countQuota1.setBalance(countQuota1.getLineOfCredit());
                        //}else if(countQuota1.getCreditType().equals(CountQuota.CreditType.quantity)){
                        countQuota1.setResidualQuantity(countQuota1.getAuthorizedQuantity());
                        //}
                    }else if(authorityManage.getLineEvaluatePeriod().equals(AuthorityManage.LineEvaluatePeriod.month)){//每月
                        countQuota1.setResetTime(LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfNextMonth()), LocalTime.MIN));
                        //if (countQuota1.getCreditType().equals(CountQuota.CreditType.money)){
                        countQuota1.setBalance(countQuota1.getLineOfCredit());
                        //}else if(countQuota1.getCreditType().equals(CountQuota.CreditType.quantity)){
                        countQuota1.setResidualQuantity(countQuota1.getAuthorizedQuantity());
                        //}
                    }else if(authorityManage.getLineEvaluatePeriod().equals(AuthorityManage.LineEvaluatePeriod.quarter)){//每季度
                        countQuota1.setResetTime(LocalDateTime.of(LocalDate.of(LocalDate.now().plusMonths(3).getYear(),LocalDate.now().plusMonths(3).getMonth().firstMonthOfQuarter(),1),LocalTime.MIN));
                        //if (countQuota1.getCreditType().equals(CountQuota.CreditType.money)){
                        countQuota1.setBalance(countQuota1.getLineOfCredit());
                        //}else if(countQuota1.getCreditType().equals(CountQuota.CreditType.quantity)){
                        countQuota1.setResidualQuantity(countQuota1.getAuthorizedQuantity());
                        //}
                    }else if(authorityManage.getLineEvaluatePeriod().equals(AuthorityManage.LineEvaluatePeriod.year)){//每年
                        countQuota1.setResetTime(LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfNextYear()), LocalTime.MIN));
                        //if (countQuota1.getCreditType().equals(CountQuota.CreditType.money)){
                        countQuota1.setBalance(countQuota1.getLineOfCredit());
                        //}else if(countQuota1.getCreditType().equals(CountQuota.CreditType.quantity)){
                        countQuota1.setResidualQuantity(countQuota1.getAuthorizedQuantity());
                        //}
                    }
                    countQuotaService.updateById(countQuota1);
                }

                QueryWrapper<AuthorityMember> authorityMemberQueryWrapper = new QueryWrapper<>();
                authorityMemberQueryWrapper.eq("authority_manage_id", authorityManage.getId());
                authorityMemberQueryWrapper.eq("user_id", JwtUtils.getLoginUserId());
                AuthorityMember authorityMember = authorityMemberService.getOne(authorityMemberQueryWrapper);
                if(null == authorityMember){
                    throw new BusinessException("超额申请记录审核失败:申请人不在该权限组! 权限组名称:" + authorityManage.getName());
                }

                Map<String, Object> parmas = new HashMap<String, Object>();
                if(authorityManage.getLineEvaluatePeriod().name().equals("day")) {//每天
                    parmas.put("startCreateTime",LocalDateTime.of(LocalDate.now(), LocalTime.MIN));
                }else if(authorityManage.getLineEvaluatePeriod().name().equals("week")){//每周
                    parmas.put("startCreateTime",LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.previous(DayOfWeek.MONDAY)), LocalTime.MIN));
                }else if(authorityManage.getLineEvaluatePeriod().name().equals("month")){//每月
                    parmas.put("startCreateTime",LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfMonth()), LocalTime.MIN));
                }else if(authorityManage.getLineEvaluatePeriod().name().equals("quarter")){//每季度
                    parmas.put("startCreateTime",LocalDateTime.of(LocalDate.of(LocalDate.now().getYear(),LocalDate.now().getMonth().firstMonthOfQuarter(),1),LocalTime.MIN));
                }else if(authorityManage.getLineEvaluatePeriod().name().equals("year")){//每年
                    parmas.put("startCreateTime",LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfYear()), LocalTime.MIN));
                }
                parmas.put("endCreateTime",LocalDateTime.now());
                parmas.put("authorityManageId", authorityManage.getId());

                if (authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.share) || authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.shareQuantity)) {
                    BigDecimal applyPrice = aboveTheQuotaApplyDao.getSumApplyPrice(parmas);
                    BigDecimal applyQuantity = aboveTheQuotaApplyDao.getSumApplyQuantity(parmas);
                    if(null == authorityManage.getCreditAmount()){
                        authorityManage.setCreditAmount(new BigDecimal(0));
                    }
                    if(null == authorityManage.getCreditQuantity()){
                        authorityManage.setCreditQuantity(0);
                    }
                    authorityManage.setPracticalCreditQuantity(authorityManage.getCreditQuantity() + applyQuantity.intValue());
                    authorityManage.setPracticalLineOfCredit(authorityManage.getCreditAmount().add(applyPrice));
                    authorityManageService.updateById(authorityManage);
                }

                if (authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.independent) || authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.independentQuantity)) {
                    parmas.put("creator", authorityMember.getUserId());
                    BigDecimal applyPrice = aboveTheQuotaApplyDao.getSumApplyPrice(parmas);
                    BigDecimal applyQuantity = aboveTheQuotaApplyDao.getSumApplyQuantity(parmas);
                    if(null == authorityManage.getCreditAmount()){
                        authorityManage.setCreditAmount(new BigDecimal(0));
                    }
                    if(null == authorityManage.getCreditQuantity()){
                        authorityManage.setCreditQuantity(0);
                    }
                    authorityMember.setPracticalCreditQuantity(authorityManage.getCreditQuantity() + applyQuantity.intValue());
                    authorityMember.setPracticalLineOfCredit(authorityManage.getCreditAmount().add(applyPrice));
                    authorityMemberService.updateById(authorityMember);
                }

                ////更新权限表和权限物料表
                //authorityManage.setPracticalLineOfCredit(authorityManage.getCreditAmount());
                //authorityManage.setPracticalCreditQuantity(authorityManage.getCreditQuantity());
                //authorityManageService.updateById(authorityManage);
                //
                ////更新权限成员表


                List<AuthorityMateriel> authorityMaterielList = authorityMaterielService.list(new QueryWrapper<AuthorityMateriel>().eq("manage_id", authorityManage.getId()));
                for(AuthorityMateriel authorityMateriel : authorityMaterielList){
                    authorityMateriel.setRealAmount(authorityMateriel.getAmount());
                    authorityMateriel.setRealNumber(authorityMateriel.getNumber());
                    authorityMaterielService.updateById(authorityMateriel);
                }
            }
        }
    }

    public void countNew(AuthorityManage authorityManageItem,CellInventoryInoutDetailForm item,ProductDetailVO productDetail){
        CountQuota countQuota = null;
        if (authorityManageItem.getCreditWay().equals(AuthorityManage.CreditWay.shareQuantity)||authorityManageItem.getCreditWay().equals(AuthorityManage.CreditWay.share)) {//共享金额或者共享数量
            countQuota = countQuotaService.getOne(new LambdaQueryWrapper<CountQuota>()
                    .eq(CountQuota::getAuthorityManageId, authorityManageItem.getId())
                    .eq(CountQuota::getSkuCode,item.getSkuCode()));
        }else{
            countQuota = countQuotaService.getOne(new LambdaQueryWrapper<CountQuota>()
                    .eq(CountQuota::getAuthorityManageId, authorityManageItem.getId())
                    .eq(CountQuota::getReceiverId, JwtUtils.getLoginUserId())
                    .eq(CountQuota::getSkuCode,item.getSkuCode()));
        }
        if(countQuota!=null){
            //当前领取的金额
            BigDecimal currentAmount = productDetail.getBasePrice().multiply(BigDecimal.valueOf(Math.abs(item.getQuantity())).multiply(BigDecimal.valueOf(item.getQuantityPackUnit())));
            //额度
            BigDecimal usableAmount =  authorityMaterielService.getOne(new QueryWrapper<AuthorityMateriel>().eq("manage_id",authorityManageItem.getId()).eq("sku_code",item.getSkuCode())).getRealAmount();

            //权限组的授信类型
            //金额
            if(authorityManageItem.getCreditType().getValue() == 0){
                //剩余可领金额
                BigDecimal surplusAmount = countQuota.getBalance().subtract(currentAmount);
                //权限组的授信方式
                if(authorityManageItem.getCreditWay().name().equals("share")){//组员共享领用金额
                    //额度评估周期
                    //异步统计
                    addReceiveRecord(authorityManageItem.getId(),authorityManageItem.getLineEvaluatePeriod().name(),item.getSkuCode()
                            ,productDetail.getMarketPrice(),item.getQuantity(),null
                            ,authorityManageItem.getCreditWay().name(),usableAmount,currentAmount);
                    List<CountQuota> countQuotaList = countQuotaService.list(new LambdaQueryWrapper<CountQuota>()
                            .eq(CountQuota::getAuthorityManageId, authorityManageItem.getId())
                            .eq(CountQuota::getCreditWay, CountQuota.CreditWay.share)
                            .eq(CountQuota::getSkuCode,item.getSkuCode()));
                    for (CountQuota countQuotaItem:countQuotaList){
                        countQuotaItem.setBalance(surplusAmount);
                        countQuotaService.updateById(countQuotaItem);
                    }
                }else if(authorityManageItem.getCreditWay().name().equals("independent")){//组员独立授信领用金额
                    //额度评估周期
                    // 如果授信类型是金额
                    countQuota.setBalance(surplusAmount);
                    countQuotaService.updateById(countQuota);
                    //异步统计
                    addReceiveRecord(authorityManageItem.getId(),authorityManageItem.getLineEvaluatePeriod().name(),item.getSkuCode()
                            ,productDetail.getMarketPrice(),item.getQuantity(),JwtUtils.getLoginUserId()
                            ,authorityManageItem.getCreditWay().name(),usableAmount,currentAmount);
                }
            }else if(authorityManageItem.getCreditWay().name().equals("unlimited")||authorityManageItem.getCreditWay().name().equals("unlimitedQuantity")){ //不限制领用金额或者数量
                //异步统计金额
                addReceiveRecord(authorityManageItem.getId(),authorityManageItem.getLineEvaluatePeriod().name(),item.getSkuCode()
                        ,productDetail.getMarketPrice(),item.getQuantity(),JwtUtils.getLoginUserId()
                        ,authorityManageItem.getCreditWay().name(),usableAmount,null);
            }else if(authorityManageItem.getCreditType().getValue() == 1){ //数量
                //当前领取的数量
                Integer currentQuantity = Math.abs(item.getQuantity())*item.getQuantityPackUnit();
                //剩余可领数量
                Integer surplusQuantity = countQuota.getResidualQuantity()-currentQuantity;
                //权限组的授信方式
                if(authorityManageItem.getCreditWay().name().equals("shareQuantity")){ //组员共享领用数量
                    //额度评估周期
                    addReceiveRecord(authorityManageItem.getId(),authorityManageItem.getLineEvaluatePeriod().name(),item.getSkuCode()
                            ,productDetail.getMarketPrice(),item.getQuantity(),null
                            ,authorityManageItem.getCreditWay().name(),usableAmount,currentAmount);
                    List<CountQuota> countQuotaList = countQuotaService.list(new LambdaQueryWrapper<CountQuota>()
                            .eq(CountQuota::getAuthorityManageId, authorityManageItem.getId())
                            .eq(CountQuota::getCreditWay, CountQuota.CreditWay.shareQuantity)
                            .eq(CountQuota::getSkuCode,item.getSkuCode()));
                    if(CollectionUtil.isNotEmpty(countQuotaList)){
                        for (CountQuota countQuotaItem:countQuotaList){
                            countQuotaItem.setResidualQuantity(surplusQuantity);
                            countQuotaService.updateById(countQuotaItem);
                        }
                    }
                }else if(authorityManageItem.getCreditWay().name().equals("independentQuantity")){//组员独立授信领用数量
                    //额度评估周期
                    // 如果授信类型是数量
                    countQuota.setResidualQuantity(surplusQuantity);
                    countQuotaService.updateById(countQuota);
                    //异步统计
                    addReceiveRecord(authorityManageItem.getId(),authorityManageItem.getLineEvaluatePeriod().name(),item.getSkuCode()
                            ,productDetail.getMarketPrice(),item.getQuantity(),JwtUtils.getLoginUserId()
                            ,authorityManageItem.getCreditWay().name(),usableAmount,currentAmount);
                }else if(authorityManageItem.getCreditWay().name().equals("unlimited")||authorityManageItem.getCreditWay().name().equals("unlimitedQuantity")){ //不限制领用金额
                    //异步统计金额
                    addReceiveRecord(authorityManageItem.getId(),authorityManageItem.getLineEvaluatePeriod().name(),item.getSkuCode()
                            ,productDetail.getMarketPrice(),item.getQuantity(),JwtUtils.getLoginUserId()
                            ,authorityManageItem.getCreditWay().name(),usableAmount,null);
                }
            }
        }
    }

    @Transactional
    public JsonResult verifyPermissionsNew(List<CellInventoryInoutDetailForm> list) {
        JSONObject jsonObject = new JSONObject();
        //查询是否有设置有效权限组，无有效权限组，随便领（防止换新没有柜子编号时的报错）
        List<AuthorityManage> allManageList = authorityManageService.list(new LambdaQueryWrapper<AuthorityManage>().eq(AuthorityManage::getStatus, "0"));
        if (allManageList.size() <= 0) {
            return JsonResult.success("操作成功", jsonObject.toJSONString());
        }
        //查询主柜
        List<Cabinet> cabinetCodes = cabinetService.list(new LambdaQueryWrapper<Cabinet>().eq(Cabinet::getCode, list.get(0).getCabCode()));
        List<Cabinet> cabinets = cabinetService.list(new LambdaQueryWrapper<Cabinet>().eq(Cabinet::getCabCode, cabinetCodes.get(0).getBelongCabinet()));
        Cabinet mainCabinet = cabinets.get(0);

        //查询是否有设置有效权限组，无有效权限组，随便领
        List<AuthorityManage> manageList = authorityManageService.list(new LambdaQueryWrapper<AuthorityManage>().eq(AuthorityManage::getStatus, "0").like(AuthorityManage::getCabinetCode, cabinetCodes.get(0).getBelongCabinet()));
        if (manageList.size() <= 0) {
            return JsonResult.success("操作成功", jsonObject.toJSONString());
        }
        //manageList.removeIf(authorityManage -> !authorityManage.getCabinetId().contains(cabinets.get(0).getId().toString()));

        //获得当前登录人所在的权限组成员列表
        //List<AuthorityMember> authorityMemberListTemp = authorityMemberService.list(new LambdaQueryWrapper<AuthorityMember>().eq(AuthorityMember::getUserId, JwtUtils.getLoginUserId()));
        Map<String, Object> memberMapParms = new HashMap<String, Object>();
        memberMapParms.put("userId", JwtUtils.getLoginUserId());
        memberMapParms.put("mainCabCode", cabinetCodes.get(0).getBelongCabinet());
        List<AuthorityMemberVO> authorityMemberListTemp =  authorityMemberDao.list4appOnCabinet(memberMapParms);
        //如果该企业有设置权限组，但是此用户不在任何一个权限组内，不能领新
        if (null == authorityMemberListTemp || authorityMemberListTemp.size() <= 0) {
            return JsonResult.fail(Result.Code.NONW_AUTH_ERROR.getCode(), "当前用户没有领新权限!如需要领新,请联系管理员为此用户添加权限组!", jsonObject.toJSONString());
        }
        AuthorityMemberVO authorityMember = authorityMemberListTemp.get(0);

        //查询当前登陆人的权限组对象
        AuthorityManage authorityManage = authorityManageService.getById(authorityMember.getAuthorityManageId());
        if (null == authorityManage || !authorityManage.getStatus().equals(0l)) {
            return JsonResult.fail(Result.Code.NONW_AUTH_ERROR.getCode(), "当前用户没有领新权限!如需要领新,请联系管理员为此用户添加权限组!", jsonObject.toJSONString());
        }

        List<AuthorityMember> authorityMemberList = authorityMemberService.list(new LambdaQueryWrapper<AuthorityMember>().eq(AuthorityMember::getAuthorityManageId, authorityManage.getId()));

        jsonObject.put("authorityManageId", authorityManage.getId());

        //当前领取的金额
        BigDecimal currentAmount = new BigDecimal(0);
        //当前领取的数量
        Integer currentQuantity = 0;
        for(CellInventoryInoutDetailForm item : list){
            ProductDetailVO productDetailVO = productDetailService.getProductDetailBySkuCode(item.getSkuCode());
            if(null == productDetailVO.getBasePrice()){
                return JsonResult.fail(Result.Code.NONW_AUTH_ERROR.getCode(), "当前用户没有领新权限!领取的物料未配置基础单价，物料编号:"+item.getSkuCode(), jsonObject.toJSONString());
            }
            item.setQuantityPackUnit(productDetailVO.getQuantityPackUnit());
            BigDecimal tempAmount = productDetailVO.getMarketPrice().multiply(BigDecimal.valueOf(Math.abs(item.getQuantity())));
            currentAmount = currentAmount.add(tempAmount);

            Integer tempQuantity = Math.abs(item.getQuantity()) * item.getQuantityPackUnit();
            currentQuantity += tempQuantity;
        }

        ////判断总体授信额度
        try {
            justTotalCredit(authorityManage, authorityMemberList, currentAmount, currentQuantity, authorityManage.getCabinetCode());
        } catch (BusinessException e) {
            return JsonResult.fail(e.getCode(), e.getMessage(), jsonObject.toJSONString());
        }

        for (CellInventoryInoutDetailForm item : list) {
            //要领取的物料
            ProductDetailVO productDetailVO = productDetailService.getProductDetailBySkuCode(item.getSkuCode());

            /**
             * 授信类型:money(0,金额);quantity(1,数量);
             * 授信方式: share(0,组员共享领用金额);independent(1,组员独立授信领用金额);unlimited(2,不限制领用金额)
             * 限定方式: noAstrict(0,不限制);astrict(1,限制)
             * 未归还阈值: 未设置、超额、未超额
             * 授信额度: 不设置额度、超额
             */

            resetTime(authorityManage);//重置时间

            //查询当前还剩余可领取数量
            CountQuota countQuota = null;
            if (authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.shareQuantity) || authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.share)) {//共享金额或者共享数量
                //共享的老数据 可能有多条
                countQuota = countQuotaService.getOne(new LambdaQueryWrapper<CountQuota>()
                        .eq(CountQuota::getAuthorityManageId, authorityManage.getId())
                        .eq(CountQuota::getSkuCode, item.getSkuCode()));
            } else {
                //非共享的 但成员去查 只一条
                countQuota = countQuotaService.getOne(new LambdaQueryWrapper<CountQuota>()
                        .eq(CountQuota::getAuthorityManageId, authorityManage.getId())
                        .eq(CountQuota::getReceiverId, JwtUtils.getLoginUserId())
                        .eq(CountQuota::getSkuCode, item.getSkuCode()));
            }

            //组员共享额度
            if (authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.share) || authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.shareQuantity)) {
                //不限制物料
                if (authorityManage.getAstrictMaterial().equals(AuthorityManage.AstrictMaterial.noAstrict)) {
                    //按金额
                    if (authorityManage.getCreditType().equals(AuthorityManage.CreditType.money)) {
                        //1.未归还的总金额
                        BigDecimal total = new BigDecimal(0);
                        //该权限组的所有成员
                        for (AuthorityMember authorityMemberTemp : authorityMemberList) {
                            //List<UseInventoryUser> useInventoryUsers = useInventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("creator", authorityMemberTemp.getUserId()).eq("cab_code", item.getCabCode()));
                            List<UseInventoryUser> useInventoryUsers = useInventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("creator", authorityMemberTemp.getUserId()));
                            for (UseInventoryUser useInventoryUser : useInventoryUsers) {
                                if (useInventoryUser.getTotal() == null) {
                                    total = total.add(new BigDecimal(0));
                                } else {
                                    total = total.add(useInventoryUser.getTotal());
                                }
                            }
                        }
                        total = total.add(currentAmount);
                        BigDecimal moneyThreshold = authorityManage.getMoneyThreshold();
                        if (total.compareTo(moneyThreshold) >=0 && moneyThreshold.compareTo(new BigDecimal(0))  != 0 ) {
                            return JsonResult.fail(Result.Code.OUT_THRESHOLD_ERROR.getCode(), "未归还金额已到达未归还金额阈值", jsonObject.toJSONString());
                        }

                        //2.判断领新金额或数量是否超额
                        if (null != countQuota) {
                            try {
                                justCreditType(item, authorityManage, productDetailVO, countQuota);
                            } catch (BusinessException e) {
                                return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(), e.getMessage(), jsonObject.toJSONString());
                            }
                        }

                    }

                    //按数量
                    if (authorityManage.getCreditType().equals(AuthorityManage.CreditType.quantity)) {
                        //未归还的数量
                        Integer qua = 0;
                        //该权限组的所有成员
                        for (AuthorityMember authorityMemberTemp : authorityMemberList) {
                            //List<UseInventoryUser> useInventoryUsers = useInventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("creator", authorityMemberTemp.getUserId()).eq("cab_code", item.getCabCode()));
                            List<UseInventoryUser> useInventoryUsers = useInventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("creator", authorityMemberTemp.getUserId()));
                            for (UseInventoryUser useInventoryUser : useInventoryUsers) {
                                qua = qua + useInventoryUser.getQuantity();
                            }
                        }
                        qua = qua + currentQuantity;
                        Integer quantityThreshold = authorityManage.getQuantityThreshold();
                        if (qua >= quantityThreshold && quantityThreshold  != 0) {
                            return JsonResult.fail(Result.Code.OUT_THRESHOLD_ERROR.getCode(), "未归还数量已到达未归还数量阈值", jsonObject.toJSONString());
                        }

                        //2.判断领新金额或数量是否超额
                        if (null != countQuota) {
                            try {
                                justCreditType(item, authorityManage, productDetailVO, countQuota);
                            } catch (BusinessException e) {
                                return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(), e.getMessage(), jsonObject.toJSONString());
                            }
                        }
                    }

                }

                //限制物料
                if (authorityManage.getAstrictMaterial().equals(AuthorityManage.AstrictMaterial.astrict)) {
                    try {
                        justMateriel(item, authorityManage, productDetailVO, countQuota, currentAmount, currentQuantity);
                    } catch (BusinessException e) {
                        return JsonResult.fail(e.getCode(), e.getMessage(), jsonObject.toJSONString());
                    }
                }

                ////判断总体授信额度
                //try {
                //    justTotalCredit(authorityManage, authorityMemberList, productDetailVO, item);
                //} catch (BusinessException e) {
                //    return JsonResult.fail(e.getCode(), e.getMessage(), jsonObject.toJSONString());
                //}

            }

            //组员独享额度
            if (authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.independent) || authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.independentQuantity)) {
                //不限制物料
                if (authorityManage.getAstrictMaterial().equals(AuthorityManage.AstrictMaterial.noAstrict)) {
                    //按金额
                    if (authorityManage.getCreditType().equals(AuthorityManage.CreditType.money)) {
                        //该人未归还的信息  即正在用的
                        BigDecimal moneyThreshold = authorityManage.getMoneyThreshold();

                        //List<UseInventoryUser> useInventoryUsers = useInventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("creator", JwtUtils.getLoginUserId()).eq("cab_code", item.getCabCode()));
                        List<UseInventoryUser> useInventoryUsers = useInventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("creator", JwtUtils.getLoginUserId()));
                        //未归还的总金额
                        BigDecimal total = new BigDecimal(0);
                        for (UseInventoryUser useInventoryUser : useInventoryUsers) {
                            total = total.add(useInventoryUser.getTotal());
                        }
                        total = total.add(currentAmount);
                        //如果该人的未归还的总金额大于权限组设置的金额未归还阈值 不让取
                        if (total.compareTo(moneyThreshold) >=0 && moneyThreshold.compareTo(new BigDecimal(0))  != 0) {
                            return JsonResult.fail(Result.Code.OUT_THRESHOLD_ERROR.getCode(), "未归还金额已到达未归还金额阈值", jsonObject.toJSONString());
                        }

                        //2.判断领新金额或数量是否超额
                        if (null != countQuota) {
                            try {
                                justCreditType(item, authorityManage, productDetailVO, countQuota);
                            } catch (BusinessException e) {
                                return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(), e.getMessage(), jsonObject.toJSONString());
                            }
                        }

                    }

                    //按数量
                    if (authorityManage.getCreditType().equals(AuthorityManage.CreditType.quantity)) {
                        Integer quantityThreshold = authorityManage.getQuantityThreshold();
                        //该人未归还的信息  即正在用的
                        //List<UseInventoryUser> useInventoryUsers = useInventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("creator", JwtUtils.getLoginUserId()).eq("cab_code", item.getCabCode()));
                        List<UseInventoryUser> useInventoryUsers = useInventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("creator", JwtUtils.getLoginUserId()));
                        //未归还的数量
                        Integer qua = 0;
                        for (UseInventoryUser useInventoryUser : useInventoryUsers) {
                            qua = qua + useInventoryUser.getQuantity();
                        }
                        qua = qua + currentQuantity;
                        //如果该人的未归还的总数量大于权限组设置的数量未归还阈值 不让取
                        if (qua >= quantityThreshold && quantityThreshold != 0) {
                            return JsonResult.fail(Result.Code.OUT_THRESHOLD_ERROR.getCode(), "未归还数量已到达未归还数量阈值", jsonObject.toJSONString());
                        }

                        //2.判断领新金额或数量是否超额
                        if (null != countQuota) {
                            try {
                                justCreditType(item, authorityManage, productDetailVO, countQuota);
                            } catch (BusinessException e) {
                                return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(), e.getMessage(), jsonObject.toJSONString());
                            }
                        }
                    }
                }

                //限制物料
                if (authorityManage.getAstrictMaterial().equals(AuthorityManage.AstrictMaterial.astrict)) {
                    try {
                        justMateriel(item, authorityManage, productDetailVO, countQuota, currentAmount, currentQuantity);
                    } catch (BusinessException e) {
                        return JsonResult.fail(e.getCode(), e.getMessage(), jsonObject.toJSONString());
                    }
                }

                ////判断总体授信额度
                //try {
                //    justTotalCredit(authorityManage, authorityMemberList, productDetailVO, item);
                //} catch (BusinessException e) {
                //    return JsonResult.fail(e.getCode(), e.getMessage(), jsonObject.toJSONString());
                //}
            }

            //不限制领取金额
            if (authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.unlimited)) {

                //限制物料
                if (authorityManage.getAstrictMaterial().equals(AuthorityManage.AstrictMaterial.astrict)) {
                    //权限组限制物料 按分类
                    if (authorityManage.getRestrictWay().equals(AuthorityManage.RestrictWay.category)) {
                        boolean flag = false;
                        String[] rangeArray = authorityManage.getMaterialId().split(",");
                        flag = Arrays.asList(rangeArray).contains(productDetailVO.getProductCategoryId().toString());
                        //这个权限组不包含要领取的物料
                        if (!flag) {
                            return JsonResult.fail(Result.Code.NONW_AUTH_ERROR.getCode(), "您没有领取" + item.getSkuCode() + "的权限,请联系管理员", jsonObject.toJSONString());
                        }
                    }

                    //权限组限制物料 按物料
                    if (authorityManage.getRestrictWay().equals(AuthorityManage.RestrictWay.materiel)) {
                        Integer c = 0;
                        //权限组可领取的sku
                        List<AuthorityMateriel> authorityMaterielList = authorityMaterielService.list(new QueryWrapper<AuthorityMateriel>().eq("manage_id", authorityManage.getId()));
                        for (AuthorityMateriel authorityMateriel : authorityMaterielList) {
                            if (productDetailVO.getSkuCode().equals(authorityMateriel.getSkuCode())) {
                                c++;
                            }
                        }
                        if (c == 0) {
                            return JsonResult.fail(Result.Code.NONW_AUTH_ERROR.getCode(), "您没有领取" + item.getSkuCode() + "的权限,请联系管理员", jsonObject.toJSONString());
                        }
                    }
                }

                //未归还 按金额
                if (authorityManage.getCreditType().equals(AuthorityManage.CreditType.money)) {
                    //1.未归还的总金额
                    BigDecimal total = new BigDecimal(0);
                    //该权限组的所有成员
                    for (AuthorityMember authorityMemberTemp : authorityMemberList) {
                        //List<UseInventoryUser> useInventoryUsers = useInventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("creator", authorityMemberTemp.getUserId()).eq("cab_code", item.getCabCode()));
                        List<UseInventoryUser> useInventoryUsers = useInventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("creator", authorityMemberTemp.getUserId()));
                        for (UseInventoryUser useInventoryUser : useInventoryUsers) {
                            if (useInventoryUser.getTotal() == null) {
                                total = total.add(new BigDecimal(0));
                            } else {
                                total = total.add(useInventoryUser.getTotal());
                            }
                        }
                    }
                    total = total.add(currentAmount);
                    BigDecimal moneyThreshold = authorityManage.getMoneyThreshold();
                    if (total.compareTo(moneyThreshold) >=0 && moneyThreshold.compareTo(new BigDecimal(0))  != 0) {
                        return JsonResult.fail(Result.Code.OUT_THRESHOLD_ERROR.getCode(), "未归还金额已到达未归还金额阈值", jsonObject.toJSONString());
                    }

                }

                //未归还 按数量
                if (authorityManage.getCreditType().equals(AuthorityManage.CreditType.quantity)) {
                    //未归还的数量
                    Integer qua = 0;
                    //该权限组的所有成员
                    for (AuthorityMember authorityMemberTemp : authorityMemberList) {
                        //List<UseInventoryUser> useInventoryUsers = useInventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("creator", authorityMemberTemp.getUserId()).eq("cab_code", item.getCabCode()));
                        List<UseInventoryUser> useInventoryUsers = useInventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("creator", authorityMemberTemp.getUserId()));
                        for (UseInventoryUser useInventoryUser : useInventoryUsers) {
                            qua = qua + useInventoryUser.getQuantity();
                        }
                    }

                    qua = qua + currentQuantity;
                    Integer quantityThreshold = authorityManage.getQuantityThreshold();
                    if (qua >= quantityThreshold && quantityThreshold != 0) {
                        return JsonResult.fail(Result.Code.OUT_THRESHOLD_ERROR.getCode(), "未归还数量已到达未归还数量阈值", jsonObject.toJSONString());
                    }


                }

            }


            //查询权限组物料表和统计表，是否是新物料，新物料需要添加记录
            AuthorityMateriel authorityMaterielDb = authorityMaterielService.getOne(new QueryWrapper<AuthorityMateriel>().eq("manage_id", authorityManage.getId()).eq("sku_code", item.getSkuCode()));
            if (null == authorityMaterielDb) {
                List<AuthorityMateriel> authorityMaterielList = authorityMaterielService.list(new QueryWrapper<AuthorityMateriel>().eq("manage_id", authorityManage.getId()));
                AuthorityMateriel authorityMateriel = new AuthorityMateriel();
                CopyOptions copyOptions = CopyOptions.create()
                        .setEditable(AuthorityMateriel.class)
                        .setIgnoreError(true)
                        .setIgnoreNullValue(true);
                BeanUtil.copyProperties(authorityMaterielList.get(0), authorityMateriel, copyOptions);
                authorityMateriel.setSkuCode(item.getSkuCode());
                if (authorityManage.getCreditType().equals(AuthorityManage.CreditType.money)) {
                    authorityMateriel.setAmount(authorityManage.getPracticalLineOfCredit());
                } else {
                    authorityMateriel.setNumber(authorityManage.getAuthorizedQuantity());
                }
                authorityMaterielService.save(authorityMateriel);
            }


        }

        //更新统计表数据
        for (CellInventoryInoutDetailForm item : list) {

            //查询当前还剩余可领取数量
            CountQuota countQuota = null;
            if (authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.shareQuantity) || authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.share)) {//共享金额或者共享数量
                //共享的老数据 可能有多条
                countQuota = countQuotaService.getOne(new LambdaQueryWrapper<CountQuota>()
                        .eq(CountQuota::getAuthorityManageId, authorityManage.getId())
                        .eq(CountQuota::getSkuCode, item.getSkuCode()));
            } else {
                //非共享的 但成员去查 只一条
                countQuota = countQuotaService.getOne(new LambdaQueryWrapper<CountQuota>()
                        .eq(CountQuota::getAuthorityManageId, authorityManage.getId())
                        .eq(CountQuota::getReceiverId, JwtUtils.getLoginUserId())
                        .eq(CountQuota::getSkuCode, item.getSkuCode()));
            }

            //要领取的物料
            ProductDetailVO productDetailVO = productDetailService.getProductDetailBySkuCode(item.getSkuCode());

            //共享金额或者共享数量
            if (authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.shareQuantity) || authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.share)) {
                CountQuota countQuotaDb = countQuotaService.getOne(new QueryWrapper<CountQuota>().eq("authority_manage_id", authorityManage.getId()).eq("sku_code", item.getSkuCode()));
                if (null == countQuotaDb) {
                    CountQuota countQuota1 = new CountQuota();
                    CopyOptions copyOptions1 = CopyOptions.create()
                            .setEditable(CountQuota.class)
                            .setIgnoreError(true)
                            .setIgnoreNullValue(true);
                    BeanUtil.copyProperties(countQuota, countQuota1, copyOptions1);
                    countQuota1.setSkuCode(item.getSkuCode());
                    countQuotaService.save(countQuota1);
                }

                countNew(authorityManage, item, productDetailVO);//修改count表
            }

            //独享金额或者独享数量
            if (authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.independent) || authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.independentQuantity)) {
                CountQuota countQuotaDb = countQuotaService.getOne(new QueryWrapper<CountQuota>().eq("authority_manage_id", authorityManage.getId()).eq("sku_code", item.getSkuCode()).eq("receiver_id", JwtUtils.getLoginUserId()));
                List<CountQuota> countQuotaList = countQuotaService.list(new QueryWrapper<CountQuota>().eq("authority_manage_id", authorityManage.getId()));
                CountQuota countQuotaTemp = countQuotaList.get(0);
                if (null == countQuotaDb) {
                    CountQuota countQuota1 = new CountQuota();
                    CopyOptions copyOptions1 = CopyOptions.create()
                            .setEditable(CountQuota.class)
                            .setIgnoreError(true)
                            .setIgnoreNullValue(true);
                    BeanUtil.copyProperties(countQuotaTemp, countQuota1, copyOptions1);
                    countQuota1.setSkuCode(item.getSkuCode());
                    countQuota1.setReceiverId(JwtUtils.getLoginUserId());
                    countQuota1.setReceiverName(JwtUtils.getLoginUsername());
                    if (authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.independent)) {//组员独立金额
                        countQuota1.setLineOfCredit(authorityManage.getPracticalLineOfCredit());
                        countQuota1.setBalance(authorityManage.getPracticalLineOfCredit());
                    }
                    if (authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.independentQuantity)) {//组员独立数量
                        countQuota1.setAuthorizedQuantity(authorityManage.getAuthorizedQuantity());
                        countQuota1.setResidualQuantity(authorityManage.getAuthorizedQuantity());
                    }
                    countQuotaService.save(countQuota1);
                }

                countNew(authorityManage, item, productDetailVO);//修改count表
            }

        }

        return JsonResult.success("操作成功", jsonObject.toJSONString());
    }

    /**
     * 判断总体授信金额 是否 超额
     */
    public void justTotalCredit(AuthorityManage authorityManage, List<AuthorityMember> authorityMemberList, BigDecimal currentAmount, Integer currentQuantity, String mainCabCodes){

        //如果是共享 和独享 的情况 下  最后需要判断整体的领用是否超额
        //判断权限组整体实际授信金额 是否超额
        //1.共享
        if (authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.share) || authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.shareQuantity)) {
            //总数量
            Integer number = 0;
            //总金额
            BigDecimal amount = new BigDecimal(0);

            Map<String,Object> param = new HashMap();
            param.put("type",2);
            param.put("endCreateTime",LocalDateTime.now());
            List<Long> creatorIds =  authorityMemberList.stream().map(AuthorityMember::getUserId).collect(Collectors.toList());
            param.put("creatorIds",creatorIds);
            if(StringUtils.isNotBlank(mainCabCodes)){
                param.put("mainCabCodes", Arrays.asList(mainCabCodes.split(",")));
            }
            if(authorityManage.getLineEvaluatePeriod().name().equals("day")) {//每天
                param.put("startCreateTime",LocalDateTime.of(LocalDate.now(), LocalTime.MIN));
            }else if(authorityManage.getLineEvaluatePeriod().name().equals("week")){//每周
                param.put("startCreateTime",LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.previous(DayOfWeek.MONDAY)), LocalTime.MIN));
            }else if(authorityManage.getLineEvaluatePeriod().name().equals("month")){//每月
                param.put("startCreateTime",LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfMonth()), LocalTime.MIN));
            }else if(authorityManage.getLineEvaluatePeriod().name().equals("quarter")){//每季度
                param.put("startCreateTime",LocalDateTime.of(LocalDate.of(LocalDate.now().getYear(),LocalDate.now().getMonth().firstMonthOfQuarter(),1),LocalTime.MIN));
            }else if(authorityManage.getLineEvaluatePeriod().name().equals("year")){//每年
                param.put("startCreateTime",LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfYear()), LocalTime.MIN));
            }
            List<CellInventoryInoutVO> cellInventoryInoutVOList = cellInventoryInoutService.list4app(param);
            param.put("operationType",2);
            param.put("businessType",4);
            List<StorageInventoryInoutVO> storageInventoryInoutVOList = storageInventoryInoutService.list4app(param);

            if (cellInventoryInoutVOList.size()>0){
                for (CellInventoryInoutVO cellInventoryInoutVO:cellInventoryInoutVOList){
                    amount = amount.add(cellInventoryInoutVO.getTotal());
                    number = number+cellInventoryInoutVO.getQuantityPack();
                }
                for (StorageInventoryInoutVO storageInventoryInoutVO:storageInventoryInoutVOList){
                    amount = amount.add(storageInventoryInoutVO.getTotal());
                    number = number+storageInventoryInoutVO.getQuantityPack();
                }
            }

            //按金额
            if (authorityManage.getCreditType().equals(AuthorityManage.CreditType.money)) {
                //  `practical_line_of_credit` decimal(20,2) DEFAULT NULL COMMENT '实际授信金额',
                //  `practical_credit_quantity` int DEFAULT NULL COMMENT '实际授信数量',
                if(authorityManage.getPracticalLineOfCredit().compareTo(amount.add(currentAmount)) < 0){
                    throw new BusinessException(Result.Code.OUT_OF_RANGE_ERROR.getCode(), "已超出当前权限组设置的授信总额,实际授信:"+authorityManage.getPracticalLineOfCredit()+",已领:" + amount);
                }
            }

            //按数量
            if (authorityManage.getCreditType().equals(AuthorityManage.CreditType.quantity)){
                if(authorityManage.getPracticalCreditQuantity() < (number + currentQuantity)){
                    throw new BusinessException(Result.Code.OUT_OF_RANGE_ERROR.getCode(), "已超出当前权限组设置的授信数量,实际授信:"+authorityManage.getPracticalCreditQuantity()+",已领:" + number);
                }
            }
        }

        //2.独享
        if (authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.independent) || authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.independentQuantity)) {
            //总数量
            Integer number = 0;
            //总金额
            BigDecimal amount = new BigDecimal(0);

            Map<String,Object> param = new HashMap();
            param.put("types",Arrays.asList("2,4".split(",")));
            param.put("endCreateTime",LocalDateTime.now());
            List<Long> creatorIds = new ArrayList<>();
            creatorIds.add(JwtUtils.getLoginUserId());
            if(StringUtils.isNotBlank(mainCabCodes)){
                param.put("mainCabCodes", Arrays.asList(mainCabCodes.split(",")));
            }
            param.put("creatorIds",creatorIds);
            if(authorityManage.getLineEvaluatePeriod().name().equals("day")) {//每天
                param.put("startCreateTime",LocalDateTime.of(LocalDate.now(), LocalTime.MIN));
            }else if(authorityManage.getLineEvaluatePeriod().name().equals("week")){//每周
                param.put("startCreateTime",LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.previous(DayOfWeek.MONDAY)), LocalTime.MIN));
            }else if(authorityManage.getLineEvaluatePeriod().name().equals("month")){//每月
                param.put("startCreateTime",LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfMonth()), LocalTime.MIN));
            }else if(authorityManage.getLineEvaluatePeriod().name().equals("quarter")){//每季度
                param.put("startCreateTime",LocalDateTime.of(LocalDate.of(LocalDate.now().getYear(),LocalDate.now().getMonth().firstMonthOfQuarter(),1),LocalTime.MIN));
            }else if(authorityManage.getLineEvaluatePeriod().name().equals("year")){//每年
                param.put("startCreateTime",LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfYear()), LocalTime.MIN));
            }
            List<CellInventoryInoutVO> cellInventoryInoutVOList = cellInventoryInoutService.list4app(param);
            //param.put("operationType",2);
            //param.put("type",4);
            //List<StorageInventoryInoutVO> storageInventoryInoutVOList = storageInventoryInoutService.list4app(param);
            if (cellInventoryInoutVOList.size()>0){
                for (CellInventoryInoutVO cellInventoryInoutVO:cellInventoryInoutVOList){
                    amount = amount.add(cellInventoryInoutVO.getTotal());
                    number = number+cellInventoryInoutVO.getQuantityPack();
                }
                //for (StorageInventoryInoutVO storageInventoryInoutVO:storageInventoryInoutVOList){
                //    amount = amount.add(storageInventoryInoutVO.getTotal());
                //    number = number+storageInventoryInoutVO.getQuantityPack();
                //}
            }
            QueryWrapper<AuthorityMember> authorityMemberQueryWrapper = new QueryWrapper<>();
            authorityMemberQueryWrapper.eq("authority_manage_id", authorityManage.getId());
            authorityMemberQueryWrapper.eq("user_id", JwtUtils.getLoginUserId());
            AuthorityMember authorityMember = authorityMemberService.getOne(authorityMemberQueryWrapper);
            if(null == authorityMember){
                throw new BusinessException(Result.Code.NONW_AUTH_ERROR.getCode(), "当前用户不存在于这个权限组:权限组名称:"+authorityManage.getName());
            }
            //按金额
            if (authorityManage.getCreditType().equals(AuthorityManage.CreditType.money)) {
                //  `practical_line_of_credit` decimal(20,2) DEFAULT NULL COMMENT '实际授信金额',
                //  `practical_credit_quantity` int DEFAULT NULL COMMENT '实际授信数量',
                if(authorityMember.getPracticalLineOfCredit().compareTo(amount.add(currentAmount)) < 0){
                    throw new BusinessException(Result.Code.OUT_OF_RANGE_ERROR.getCode(), "已超出当前权限组设置的授信总额,实际授信:"+authorityMember.getPracticalLineOfCredit()+",已领:" + amount);
                }
            }

            //按数量
            if (authorityManage.getCreditType().equals(AuthorityManage.CreditType.quantity)){
                if(authorityMember.getPracticalCreditQuantity() < (number + currentQuantity)){
                    throw new BusinessException(Result.Code.OUT_OF_RANGE_ERROR.getCode(), "已超出当前权限组设置的授信数量,实际授信:"+authorityMember.getPracticalCreditQuantity()+",已领:" + number);
                }
            }
        }
    }

    /**
     * 判断是否超过领取金额或数量
     * @param item
     * @param authorityManage
     * @param productDetailVO
     * @throws BusinessException
     */
    public void justCreditType(CellInventoryInoutDetailForm item, AuthorityManage authorityManage, ProductDetailVO productDetailVO, CountQuota countQuota) throws BusinessException{

        //当前领取的金额
        BigDecimal currentAmount = productDetailVO.getBasePrice().multiply(BigDecimal.valueOf(Math.abs(item.getQuantity())).multiply(BigDecimal.valueOf(item.getQuantityPackUnit())));

        //单个物料默认限制状态: 0 限制  1不限制
        if(authorityManage.getAuthotizedStatus() == 0) {
            //金额
            if (authorityManage.getCreditType().getValue() == 0) {
                //权限组的授信方式
                //组员共享领用金额
                if (authorityManage.getCreditWay().name().equals("share")) {
                    //额度评估周期
                    if (authorityManage.getLineEvaluatePeriod().name().equals("day")) {//每天
                        // 如果授信类型是金额
                        if (currentAmount.compareTo(countQuota.getBalance()) == 1) {
                            throw new BusinessException(Result.Code.OUT_OF_RANGE_ERROR.getCode(), "已超出每天领取的最大金额,当前可领:" + countQuota.getBalance());
                        }
                    } else if (authorityManage.getLineEvaluatePeriod().name().equals("week")) {//每周
                        // 如果授信类型是金额
                        if (currentAmount.compareTo(countQuota.getBalance()) == 1) {
                            throw new BusinessException(Result.Code.OUT_OF_RANGE_ERROR.getCode(), "已超出每周领取的最大金额,当前可领:" + countQuota.getBalance());
                        }
                    } else if (authorityManage.getLineEvaluatePeriod().name().equals("month")) {//每月
                        // 如果授信类型是金额
                        if (currentAmount.compareTo(countQuota.getBalance()) == 1) {
                            throw new BusinessException(Result.Code.OUT_OF_RANGE_ERROR.getCode(), "已超出每月领取的最大金额,当前可领:" + countQuota.getBalance());
                        }
                    } else if (authorityManage.getLineEvaluatePeriod().name().equals("quarter")) {//每季度
                        // 如果授信类型是金额
                        if (currentAmount.compareTo(countQuota.getBalance()) == 1) {
                            throw new BusinessException(Result.Code.OUT_OF_RANGE_ERROR.getCode(), "已超出每季度领取的最大金额,当前可领:" + countQuota.getBalance());
                        }
                    } else if (authorityManage.getLineEvaluatePeriod().name().equals("year")) {//每年
                        // 如果授信类型是金额
                        if (currentAmount.compareTo(countQuota.getBalance()) == 1) {
                            throw new BusinessException(Result.Code.OUT_OF_RANGE_ERROR.getCode(), "已超出每年领取的最大金额,当前可领:" + countQuota.getBalance());
                        }
                    }

                }
                //组员独立授信领用金额
                if (authorityManage.getCreditWay().name().equals("independent")) {
                    //额度评估周期
                    if (authorityManage.getLineEvaluatePeriod().name().equals("day")) {//每天
                        // 如果授信类型是金额
                        if (currentAmount.compareTo(countQuota.getBalance()) == 1) {
                            throw new BusinessException(Result.Code.OUT_OF_RANGE_ERROR.getCode(), "已超出每天领取的最大金额,当前可领:" + countQuota.getBalance());
                        }
                    } else if (authorityManage.getLineEvaluatePeriod().name().equals("week")) {//每周
                        // 如果授信类型是金额
                        if (currentAmount.compareTo(countQuota.getBalance()) == 1) {
                            throw new BusinessException(Result.Code.OUT_OF_RANGE_ERROR.getCode(), "已超出每周领取的最大金额,当前可领:" + countQuota.getBalance());
                        }
                    } else if (authorityManage.getLineEvaluatePeriod().name().equals("month")) {//每月
                        // 如果授信类型是金额
                        if (currentAmount.compareTo(countQuota.getBalance()) == 1) {
                            throw new BusinessException(Result.Code.OUT_OF_RANGE_ERROR.getCode(), "已超出每月领取的最大金额,当前可领:" + countQuota.getBalance());
                        }
                    } else if (authorityManage.getLineEvaluatePeriod().name().equals("quarter")) {//每季度
                        // 如果授信类型是金额
                        if (currentAmount.compareTo(countQuota.getBalance()) == 1) {
                            throw new BusinessException(Result.Code.OUT_OF_RANGE_ERROR.getCode(), "已超出每季度领取的最大金额,当前可领:" + countQuota.getBalance());
                        }
                    } else if (authorityManage.getLineEvaluatePeriod().name().equals("year")) {//每年
                        // 如果授信类型是金额
                        if (currentAmount.compareTo(countQuota.getBalance()) == 1) {
                            throw new BusinessException(Result.Code.OUT_OF_RANGE_ERROR.getCode(), "已超出每年领取的最大金额,当前可领:" + countQuota.getBalance());
                        }
                    }
                }
            }
            //数量
            if (authorityManage.getCreditType().getValue() == 1) {
                //当前领取的数量
                Integer currentQuantity = Math.abs(item.getQuantity()) * item.getQuantityPackUnit();
                //权限组的授信方式
                if (authorityManage.getCreditWay().name().equals("shareQuantity")) { //组员共享领用数量
                    //额度评估周期
                    if (authorityManage.getLineEvaluatePeriod().name().equals("day")) {//每天
                        // 如果授信类型是数量
                        if (currentQuantity > countQuota.getResidualQuantity()) {
                            throw new BusinessException(Result.Code.OUT_OF_RANGE_ERROR.getCode(), "已超出每天领取的最大数量,当前可领:" + countQuota.getResidualQuantity());
                        }
                    } else if (authorityManage.getLineEvaluatePeriod().name().equals("week")) {//每周
                        // 如果授信类型是数量
                        if (currentQuantity > countQuota.getResidualQuantity()) {
                            throw new BusinessException(Result.Code.OUT_OF_RANGE_ERROR.getCode(), "已超出每周领取的最大数量:" + countQuota.getResidualQuantity());
                        }
                    } else if (authorityManage.getLineEvaluatePeriod().name().equals("month")) {//每月
                        // 如果授信类型是数量
                        if (currentQuantity > countQuota.getResidualQuantity()) {
                            throw new BusinessException(Result.Code.OUT_OF_RANGE_ERROR.getCode(), "已超出每月领取的最大数量:" + countQuota.getResidualQuantity());
                        }
                    } else if (authorityManage.getLineEvaluatePeriod().name().equals("quarter")) {//每季度
                        // 如果授信类型是数量
                        if (currentQuantity > countQuota.getResidualQuantity()) {
                            throw new BusinessException(Result.Code.OUT_OF_RANGE_ERROR.getCode(), "已超出每季度领取的最大数量:" + countQuota.getResidualQuantity());
                        }
                    } else if (authorityManage.getLineEvaluatePeriod().name().equals("year")) {//每年
                        // 如果授信类型是数量
                        if (currentQuantity > countQuota.getResidualQuantity()) {
                            throw new BusinessException(Result.Code.OUT_OF_RANGE_ERROR.getCode(), "已超出每年领取的最大数量:" + countQuota.getResidualQuantity());
                        }
                    }
                } else if (authorityManage.getCreditWay().name().equals("independentQuantity")) {//组员独立授信领用数量
                    //额度评估周期
                    if (authorityManage.getLineEvaluatePeriod().name().equals("day")) {//每天
                        // 如果授信类型是数量
                        if (currentQuantity > countQuota.getResidualQuantity()) {
                            throw new BusinessException(Result.Code.OUT_OF_RANGE_ERROR.getCode(), "已超出每天领取的最大数量:" + countQuota.getResidualQuantity());
                        }
                    } else if (authorityManage.getLineEvaluatePeriod().name().equals("week")) {//每周
                        // 如果授信类型是数量
                        if (currentQuantity > countQuota.getResidualQuantity()) {
                            throw new BusinessException(Result.Code.OUT_OF_RANGE_ERROR.getCode(), "已超出每周领取的最大数量:" + countQuota.getResidualQuantity());
                        }
                    } else if (authorityManage.getLineEvaluatePeriod().name().equals("month")) {//每月
                        // 如果授信类型是数量
                        if (currentQuantity > countQuota.getResidualQuantity()) {
                            throw new BusinessException(Result.Code.OUT_OF_RANGE_ERROR.getCode(), "已超出每月领取的最大数量:" + countQuota.getResidualQuantity());
                        }
                    } else if (authorityManage.getLineEvaluatePeriod().name().equals("quarter")) {//每季度
                        // 如果授信类型是数量
                        if (currentQuantity > countQuota.getResidualQuantity()) {
                            throw new BusinessException(Result.Code.OUT_OF_RANGE_ERROR.getCode(), "已超出每季度领取的最大数量:" + countQuota.getResidualQuantity());
                        }
                    } else if (authorityManage.getLineEvaluatePeriod().name().equals("year")) {//每年
                        // 如果授信类型是数量
                        if (currentQuantity > countQuota.getResidualQuantity()) {
                            throw new BusinessException(Result.Code.OUT_OF_RANGE_ERROR.getCode(), "已超出每年领取的最大数量:" + countQuota.getResidualQuantity());
                        }
                    }
                }
            }

        }

    }

    /**
     * 判断限制物料：按物料/按分类
     * @param item
     * @param authorityManage
     * @param productDetailVO
     * @param countQuota
     * @throws BusinessException
     */
    public void justMateriel(CellInventoryInoutDetailForm item, AuthorityManage authorityManage, ProductDetailVO productDetailVO, CountQuota countQuota, BigDecimal currentAmount, Integer currentQuantity) throws BusinessException{
        //权限组限制物料 按分类
        if (authorityManage.getRestrictWay().equals(AuthorityManage.RestrictWay.category)) {
            boolean flag = false;
            String[] rangeArray = authorityManage.getMaterialId().split(",");
            flag=Arrays.asList(rangeArray).contains(productDetailVO.getProductCategoryId().toString());
            //这个权限组不包含要领取的物料
            if(!flag){
                throw new BusinessException(Result.Code.NONW_AUTH_ERROR.getCode(),"您没有领取"+item.getSkuCode()+"的权限,请联系管理员");
            }

            //这个权限组包含要领取的物料
            if(flag){
                //检查未归还的情况
                List<AuthorityMember> authorityMembers = authorityMemberService.list(new LambdaQueryWrapper<AuthorityMember>().eq(AuthorityMember::getAuthorityManageId, authorityManage.getId()));
                //权限组按金额授信
                if (authorityManage.getCreditType().equals(AuthorityManage.CreditType.money)){

                    //权限组设置的金额未归还阈值
                    BigDecimal moneyThreshold = authorityManage.getMoneyThreshold();
                    //组员独享金额 只看着一个人的
                    if (authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.independent)){
                        //该人未归还的信息  即正在用的
                        //List<UseInventoryUser> useInventoryUsers =  useInventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("creator",JwtUtils.getLoginUserId()).eq("cab_code",item.getCabCode()));
                        List<UseInventoryUser> useInventoryUsers =  useInventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("creator",JwtUtils.getLoginUserId()));
                        //未归还的总金额
                        BigDecimal total = new BigDecimal(0);
                        for (UseInventoryUser useInventoryUser:useInventoryUsers){
                            total=total.add(useInventoryUser.getTotal());
                        }
                        total=total.add(currentAmount);
                        //如果该人的未归还的总金额大于权限组设置的金额未归还阈值 不让取
                        if(total.compareTo(moneyThreshold)>=0 && moneyThreshold.compareTo(new BigDecimal(0))  != 0){
                            throw new BusinessException(Result.Code.OUT_THRESHOLD_ERROR.getCode(),"未归还金额已到达未归还金额阈值");
                        }
                    }

                    //组员共享金额或者不限制金额 看全组的
                    if(authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.share)||authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.unlimited)){

                        //未归还的总金额
                        BigDecimal total = new BigDecimal(0);
                        //该权限组的所有成员
                        for (AuthorityMember authorityMember:authorityMembers){
                            List<UseInventoryUser> useInventoryUsers =  useInventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("creator",authorityMember.getUserId()).eq("cab_code",item.getCabCode()));
                            for (UseInventoryUser useInventoryUser:useInventoryUsers){
                                if(useInventoryUser.getTotal()==null){
                                    total=total.add(new BigDecimal(0));
                                }else{
                                    total=total.add(useInventoryUser.getTotal());
                                }
                            }
                        }
                        if(total.compareTo(moneyThreshold)>=0 && moneyThreshold.compareTo(new BigDecimal(0))  != 0){
                            throw new BusinessException(Result.Code.OUT_THRESHOLD_ERROR.getCode(),"未归还金额已到达未归还金额阈值");
                        }
                    }
                }

                //权限组按数量授信
                if(authorityManage.getCreditType().equals(AuthorityManage.CreditType.quantity)){

                    //权限组设置的数量未归还阈值
                    Integer quantityThreshold = authorityManage.getQuantityThreshold();
                    //组员独享数量 只看这一个人的
                    if (authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.independentQuantity)){
                        //该人未归还的信息  即正在用的
                        //List<UseInventoryUser> useInventoryUsers =  useInventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("creator",JwtUtils.getLoginUserId()).eq("cab_code",item.getCabCode()));
                        List<UseInventoryUser> useInventoryUsers =  useInventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("creator",JwtUtils.getLoginUserId()));
                        //未归还的数量
                        Integer qua = 0;
                        for (UseInventoryUser useInventoryUser:useInventoryUsers){
                            qua=qua+useInventoryUser.getQuantity();
                        }
                        qua=qua+currentQuantity;
                        //如果该人的未归还的总数量大于权限组设置的数量未归还阈值 不让取
                        if(qua>=quantityThreshold && quantityThreshold!= 0){
                            throw new BusinessException(Result.Code.OUT_THRESHOLD_ERROR.getCode(),"未归还数量已到达未归还数量阈值");
                        }
                    }

                    //组员共享数量或者不限制数量 看全组的
                    if(authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.shareQuantity)||authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.unlimitedQuantity)){

                        //未归还的数量
                        Integer qua = 0;
                        //该权限组的所有成员
                        for (AuthorityMember authorityMember:authorityMembers){
                            List<UseInventoryUser> useInventoryUsers =  useInventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("creator",authorityMember.getUserId()).eq("cab_code",item.getCabCode()));
                            for (UseInventoryUser useInventoryUser:useInventoryUsers){
                                qua=qua+useInventoryUser.getQuantity();
                            }
                        }
                        if(qua>=quantityThreshold && quantityThreshold !=0){
                            throw new BusinessException(Result.Code.OUT_THRESHOLD_ERROR.getCode(),"未归还数量已到达未归还数量阈值");
                        }
                    }
                }

                resetTime(authorityManage);//重置时间

                //检查当次领取是否超过限制数量或者金额
                if(countQuota!=null){
                    try{
                        justCreditType(item, authorityManage, productDetailVO, countQuota);
                    }catch (BusinessException e){
                        throw new BusinessException(Result.Code.OUT_OF_RANGE_ERROR.getCode(),e.getMessage());
                    }
                }



            }

        }

        //权限组限制物料 按物料
        if(authorityManage.getRestrictWay().equals(AuthorityManage.RestrictWay.materiel)) {
            Integer c = 0;
            //权限组可领取的sku
            List<AuthorityMateriel> authorityMaterielList = authorityMaterielService.list(new QueryWrapper<AuthorityMateriel>().eq("manage_id", authorityManage.getId()));
            for (AuthorityMateriel authorityMateriel : authorityMaterielList) {
                if (productDetailVO.getSkuCode().equals(authorityMateriel.getSkuCode())) {
                    c++;
                }
            }
            if(c == 0){
                throw new BusinessException(Result.Code.NONW_AUTH_ERROR.getCode(),"您没有领取"+item.getSkuCode()+"的权限,请联系管理员");
            }
            if (c != 0){
                //检查未归还的情况
                List<AuthorityMember> authorityMembers = authorityMemberService.list(new LambdaQueryWrapper<AuthorityMember>().eq(AuthorityMember::getAuthorityManageId, authorityManage.getId()));

                //权限组按金额授信
                if (authorityManage.getCreditType().equals(AuthorityManage.CreditType.money)){

                    //权限组设置的金额未归还阈值
                    BigDecimal moneyThreshold = authorityManage.getMoneyThreshold();
                    //组员独享金额 只看着一个人的
                    if (authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.independent)){
                        //该人未归还的信息  即正在用的
                        //List<UseInventoryUser> useInventoryUsers =  useInventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("creator",JwtUtils.getLoginUserId()).eq("cab_code",item.getCabCode()));
                        List<UseInventoryUser> useInventoryUsers =  useInventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("creator",JwtUtils.getLoginUserId()));
                        //未归还的总金额
                        BigDecimal total = new BigDecimal(0);
                        for (UseInventoryUser useInventoryUser:useInventoryUsers){
                            total=total.add(useInventoryUser.getTotal());
                        }
                        total=total.add(currentAmount);
                        //如果该人的未归还的总金额大于权限组设置的金额未归还阈值 不让取
                        if(total.compareTo(moneyThreshold)>=0 && moneyThreshold.compareTo(new BigDecimal(0))  != 0){
                            throw new BusinessException(Result.Code.OUT_THRESHOLD_ERROR.getCode(),"未归还金额已到达未归还金额阈值");
                        }
                    }

                    //组员共享金额或者不限制金额 看全组的
                    if(authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.share)||authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.unlimited)){

                        //未归还的总金额
                        BigDecimal total = new BigDecimal(0);
                        //该权限组的所有成员
                        for (AuthorityMember authorityMember:authorityMembers){
                            //List<UseInventoryUser> useInventoryUsers =  useInventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("creator",authorityMember.getUserId()).eq("cab_code",item.getCabCode()));
                            List<UseInventoryUser> useInventoryUsers =  useInventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("creator",authorityMember.getUserId()));
                            for (UseInventoryUser useInventoryUser:useInventoryUsers){
                                if(useInventoryUser.getTotal()==null){
                                    total=total.add(new BigDecimal(0));
                                }else{
                                    total=total.add(useInventoryUser.getTotal());
                                }
                            }
                        }
                        if(total.compareTo(moneyThreshold)>=0 && moneyThreshold.compareTo(new BigDecimal(0))  != 0){
                            throw new BusinessException(Result.Code.OUT_THRESHOLD_ERROR.getCode(),"未归还金额已到达未归还金额阈值");
                        }
                    }
                }

                //权限组按数量授信
                if(authorityManage.getCreditType().equals(AuthorityManage.CreditType.quantity)){

                    //权限组设置的数量未归还阈值
                    Integer quantityThreshold = authorityManage.getQuantityThreshold();
                    //组员独享数量 只看这一个人的
                    if (authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.independentQuantity)){
                        //该人未归还的信息  即正在用的
                        //List<UseInventoryUser> useInventoryUsers =  useInventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("creator",JwtUtils.getLoginUserId()).eq("cab_code",item.getCabCode()));
                        List<UseInventoryUser> useInventoryUsers =  useInventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("creator",JwtUtils.getLoginUserId()));
                        //未归还的数量
                        Integer qua = 0;
                        for (UseInventoryUser useInventoryUser:useInventoryUsers){
                            qua=qua+useInventoryUser.getQuantity();
                        }
                        qua=qua+currentQuantity;
                        //如果该人的未归还的总数量大于权限组设置的数量未归还阈值 不让取
                        if(qua>=quantityThreshold && quantityThreshold !=0){
                            throw new BusinessException(Result.Code.OUT_THRESHOLD_ERROR.getCode(),"未归还数量已到达未归还数量阈值");
                        }
                    }

                    //组员共享数量或者不限制数量 看全组的
                    if(authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.shareQuantity)||authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.unlimitedQuantity)){

                        //未归还的数量
                        Integer qua = 0;
                        //该权限组的所有成员
                        for (AuthorityMember authorityMember:authorityMembers){
                            //List<UseInventoryUser> useInventoryUsers =  useInventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("creator",authorityMember.getUserId()).eq("cab_code",item.getCabCode()));
                            List<UseInventoryUser> useInventoryUsers =  useInventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("creator",authorityMember.getUserId()));
                            for (UseInventoryUser useInventoryUser:useInventoryUsers){
                                qua=qua+useInventoryUser.getQuantity();
                            }
                        }
                        if(qua>=quantityThreshold && quantityThreshold!=0){
                            throw new BusinessException(Result.Code.OUT_THRESHOLD_ERROR.getCode(),"未归还数量已到达未归还数量阈值");
                        }
                    }
                }


                resetTime(authorityManage);//重置时间

                //检查当次领取是否超过限制数量或者金额
                if(countQuota!=null){
                    try{
                        justCreditType(item, authorityManage, productDetailVO, countQuota);
                    }catch (BusinessException e){
                        throw new BusinessException(Result.Code.OUT_OF_RANGE_ERROR.getCode(),e.getMessage());
                    }
                }


            }

        }
    }

    @Transactional
    @Override
    public JsonResult verifyPermissions(List<CellInventoryInoutDetailForm> list){
        //根据cabCode查询主柜
        List<Cabinet> cabinetCodes = cabinetService.list(new LambdaQueryWrapper<Cabinet>().eq(Cabinet::getCode, list.get(0).getCabCode()));
        List<Cabinet> cabinets = cabinetService.list(new LambdaQueryWrapper<Cabinet>().eq(Cabinet::getCabCode, cabinetCodes.get(0).getBelongCabinet()));
        //查找该柜子上的启用状态的权限组
        /*List<AuthorityManage> manageList = authorityManageService.list(new LambdaQueryWrapper<AuthorityManage>()
                .eq(AuthorityManage::getCabinetId, cabinets.get(0).getId()).eq(AuthorityManage::getStatus,0l));*/
        List<AuthorityManage> manageList = authorityManageService.list(new LambdaQueryWrapper<AuthorityManage>().eq(AuthorityManage::getStatus,0l));
        if (manageList.size()>0){
            manageList.removeIf(authorityManage -> !authorityManage.getCabinetId().contains(cabinets.get(0).getId().toString()));
        }
        //获得当前登录人所在的权限组
        List<AuthorityMember> authorityMemberList = authorityMemberService.list(new LambdaQueryWrapper<AuthorityMember>().eq(AuthorityMember::getUserId, JwtUtils.getLoginUserId()));

        //先看该用户对该物料是否有权限领取    排除掉所有不能领的情况
        for(CellInventoryInoutDetailForm item:list){
            //要领取的物料
            ProductDetailVO productDetailVO = productDetailService.getProductDetailBySkuCode(item.getSkuCode());
            if (manageList.size()>0){//正在领料的柜子上有权限组
                if(authorityMemberList.size()>0){
                    //当前登录人有权限组
                    //查看当前登录人所在的权限组是否在该柜子上
                    Integer a =0;
                    Long id = null;
                    loop : for(AuthorityManage authorityManageItem:manageList){
                        for(AuthorityMember authorityMember:authorityMemberList){
                            if (authorityManageItem.getId()==authorityMember.getAuthorityManageId()){
                                a++;
                                id=authorityManageItem.getId();
                                break loop;
                            }
                        }
                    }
                    if (a>0) {
                        //当前登录人所在的权限组在该柜子上
                        //看权限组是否包含要领的物料
                        //包含 看权限组怎么限制的  来领取
                        //不包含 看这个物料是否在别的权限组上，在不能领，不在，能领
                        AuthorityManage  authorityManageItem = authorityManageService.getById(id);
                        if (authorityManageItem.getAstrictMaterial().equals(AuthorityManage.AstrictMaterial.noAstrict)){//权限组不限制物料  即 管控全部的物料
                            //检查未归还的情况
                            List<AuthorityMember> authorityMembers = authorityMemberService.list(new LambdaQueryWrapper<AuthorityMember>().eq(AuthorityMember::getAuthorityManageId, authorityManageItem.getId()));
                            if (authorityManageItem.getCreditType().equals(AuthorityManage.CreditType.money)){
                                //权限组按金额授信
                                //权限组设置的金额未归还阈值
                                BigDecimal moneyThreshold = authorityManageItem.getMoneyThreshold();
                                //组员独享金额 只看着一个人的
                                if (authorityManageItem.getCreditWay().equals(AuthorityManage.CreditWay.independent)){
                                    //该人未归还的信息  即正在用的
                                    List<UseInventoryUser> useInventoryUsers =  useInventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("creator",JwtUtils.getLoginUserId()).eq("cab_code",item.getCabCode()));
                                    //未归还的总金额
                                    BigDecimal total = new BigDecimal(0);
                                    for (UseInventoryUser useInventoryUser:useInventoryUsers){
                                        total=total.add(useInventoryUser.getTotal());
                                    }
                                    //如果该人的未归还的总金额大于权限组设置的金额未归还阈值 不让取
                                    if(total.compareTo(moneyThreshold)==1||total.compareTo(moneyThreshold)==0){
                                        return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"未归还金额已到达未归还金额阈值");
                                    }
                                }else if(authorityManageItem.getCreditWay().equals(AuthorityManage.CreditWay.share)||authorityManageItem.getCreditWay().equals(AuthorityManage.CreditWay.unlimited)){
                                    //组员共享金额或者不限制金额 看全组的
                                    //未归还的总金额
                                    BigDecimal total = new BigDecimal(0);
                                    //该权限组的所有成员
                                    for (AuthorityMember authorityMember:authorityMembers){
                                        List<UseInventoryUser> useInventoryUsers =  useInventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("creator",authorityMember.getUserId()).eq("cab_code",item.getCabCode()));
                                        for (UseInventoryUser useInventoryUser:useInventoryUsers){
                                            if(useInventoryUser.getTotal()==null){
                                                total=total.add(new BigDecimal(0));
                                            }else{
                                                total=total.add(useInventoryUser.getTotal());
                                            }
                                        }
                                    }
                                    if(total.compareTo(moneyThreshold)==1||total.compareTo(moneyThreshold)==0){
                                        return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"未归还金额已到达未归还金额阈值");
                                    }
                                }
                            }else{
                                //权限组按数量授信
                                //权限组设置的数量未归还阈值
                                Integer quantityThreshold = authorityManageItem.getQuantityThreshold();
                                //组员独享数量 只看这一个人的
                                if (authorityManageItem.getCreditWay().equals(AuthorityManage.CreditWay.independentQuantity)){
                                    //该人未归还的信息  即正在用的
                                    List<UseInventoryUser> useInventoryUsers =  useInventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("creator",JwtUtils.getLoginUserId()).eq("cab_code",item.getCabCode()));
                                    //未归还的数量
                                    Integer qua = 0;
                                    for (UseInventoryUser useInventoryUser:useInventoryUsers){
                                        qua=qua+useInventoryUser.getQuantity();
                                    }
                                    //如果该人的未归还的总数量大于权限组设置的数量未归还阈值 不让取
                                    if(qua>=quantityThreshold){
                                        return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"未归还数量已到达未归还数量阈值");
                                    }
                                }else if(authorityManageItem.getCreditWay().equals(AuthorityManage.CreditWay.shareQuantity)||authorityManageItem.getCreditWay().equals(AuthorityManage.CreditWay.unlimitedQuantity)){
                                    //组员共享数量或者不限制数量 看全组的
                                    //未归还的数量
                                    Integer qua = 0;
                                    //该权限组的所有成员
                                    for (AuthorityMember authorityMember:authorityMembers){
                                        List<UseInventoryUser> useInventoryUsers =  useInventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("creator",authorityMember.getUserId()).eq("cab_code",item.getCabCode()));
                                        for (UseInventoryUser useInventoryUser:useInventoryUsers){
                                            qua=qua+useInventoryUser.getQuantity();
                                        }
                                    }
                                    if(qua>=quantityThreshold){
                                        return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"未归还数量已到达未归还数量阈值");
                                    }
                                }
                            }

                            resetTime(authorityManageItem);//重置时间


                            //检查当次领取是否超过限制数量或者金额
                            CountQuota countQuota = null;
                            if (authorityManageItem.getCreditWay().equals(AuthorityManage.CreditWay.shareQuantity)||authorityManageItem.getCreditWay().equals(AuthorityManage.CreditWay.share)){//共享金额或者共享数量
                                //共享的老数据 可能有多条
                                countQuota = countQuotaService.getOne(new LambdaQueryWrapper<CountQuota>()
                                        .eq(CountQuota::getAuthorityManageId, authorityManageItem.getId())
                                        .eq(CountQuota::getSkuCode,item.getSkuCode()));
                            }else{
                                //非共享的 但成员去查 只一条
                                countQuota = countQuotaService.getOne(new LambdaQueryWrapper<CountQuota>()
                                        .eq(CountQuota::getAuthorityManageId, authorityManageItem.getId())
                                        .eq(CountQuota::getReceiverId, JwtUtils.getLoginUserId())
                                        .eq(CountQuota::getSkuCode,item.getSkuCode()));
                            }
                            if(countQuota!=null){
                                //当前领取的金额
                                BigDecimal currentAmount = productDetailVO.getMarketPrice().multiply(BigDecimal.valueOf(Math.abs(item.getQuantity())).multiply(BigDecimal.valueOf(item.getQuantityPackUnit())));

                                //权限组的授信类型
                                //金额
                                if(authorityManageItem.getCreditType().getValue() == 0){
                                    //权限组的授信方式
                                    //组员共享领用金额
                                    if(authorityManageItem.getCreditWay().name().equals("share")){
                                        //额度评估周期
                                        if(authorityManageItem.getLineEvaluatePeriod().name().equals("day")){//每天
                                            // 如果授信类型是金额
                                            if(currentAmount.compareTo(countQuota.getBalance()) == 1){
                                                return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每天领取的最大金额");
                                            }
                                        }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("week")){//每周
                                            // 如果授信类型是金额
                                            if(currentAmount.compareTo(countQuota.getBalance()) == 1){
                                                return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每周领取的最大金额");
                                            }
                                        }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("month")){//每月
                                            // 如果授信类型是金额
                                            if(currentAmount.compareTo(countQuota.getBalance()) == 1){
                                                return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每月领取的最大金额");
                                            }
                                        }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("quarter")){//每季度
                                            // 如果授信类型是金额
                                            if(currentAmount.compareTo(countQuota.getBalance()) == 1){
                                                return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每季度领取的最大金额");
                                            }
                                        }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("year")){//每年
                                            // 如果授信类型是金额
                                            if(currentAmount.compareTo(countQuota.getBalance()) == 1){
                                                return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每年领取的最大金额");
                                            }
                                        }
                                    }else if(authorityManageItem.getCreditWay().name().equals("independent")){//组员独立授信领用金额
                                        //额度评估周期
                                        if(authorityManageItem.getLineEvaluatePeriod().name().equals("day")){//每天
                                            // 如果授信类型是金额
                                            if(currentAmount.compareTo(countQuota.getBalance()) == 1){
                                                return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每天领取的最大金额");
                                            }
                                        }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("week")){//每周
                                            // 如果授信类型是金额
                                            if(currentAmount.compareTo(countQuota.getBalance()) == 1){
                                                return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每周领取的最大金额");
                                            }
                                        }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("month")){//每月
                                            // 如果授信类型是金额
                                            if(currentAmount.compareTo(countQuota.getBalance()) == 1){
                                                return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每月领取的最大金额");
                                            }
                                        }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("quarter")){//每季度
                                            // 如果授信类型是金额
                                            if(currentAmount.compareTo(countQuota.getBalance()) == 1){
                                                return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每季度领取的最大金额");
                                            }
                                        }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("year")){//每年
                                            // 如果授信类型是金额
                                            if(currentAmount.compareTo(countQuota.getBalance()) == 1){
                                                return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每年领取的最大金额");
                                            }
                                        }
                                    }
                                }else if(authorityManageItem.getCreditType().getValue() == 1){ //数量
                                    //当前领取的数量
                                    Integer currentQuantity = Math.abs(item.getQuantity())*item.getQuantityPackUnit();
                                    //权限组的授信方式
                                    if(authorityManageItem.getCreditWay().name().equals("shareQuantity")){ //组员共享领用数量
                                        //额度评估周期
                                        if(authorityManageItem.getLineEvaluatePeriod().name().equals("day")){//每天
                                            // 如果授信类型是数量
                                            if(currentQuantity>countQuota.getResidualQuantity()){
                                                return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每天领取的最大数量");
                                            }
                                        }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("week")){//每周
                                            // 如果授信类型是数量
                                            if(currentQuantity>countQuota.getResidualQuantity()){
                                                return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每周领取的最大数量");
                                            }
                                        }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("month")){//每月
                                            // 如果授信类型是数量
                                            if(currentQuantity>countQuota.getResidualQuantity()){
                                                return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每月领取的最大数量");
                                            }
                                        }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("quarter")){//每季度
                                            // 如果授信类型是数量
                                            if(currentQuantity>countQuota.getResidualQuantity()){
                                                return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每季度领取的最大数量");
                                            }
                                        }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("year")){//每年
                                            // 如果授信类型是数量
                                            if(currentQuantity>countQuota.getResidualQuantity()){
                                                return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每年领取的最大数量");
                                            }
                                        }
                                    }else if(authorityManageItem.getCreditWay().name().equals("independentQuantity")){//组员独立授信领用数量
                                        //额度评估周期
                                        if(authorityManageItem.getLineEvaluatePeriod().name().equals("day")){//每天
                                            // 如果授信类型是数量
                                            if(currentQuantity>countQuota.getResidualQuantity()){
                                                return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每天领取的最大数量");
                                            }
                                        }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("week")){//每周
                                            // 如果授信类型是数量
                                            if(currentQuantity>countQuota.getResidualQuantity()){
                                                return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每周领取的最大数量");
                                            }
                                        }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("month")){//每月
                                            // 如果授信类型是数量
                                            if(currentQuantity>countQuota.getResidualQuantity()){
                                                return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每月领取的最大数量");
                                            }
                                        }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("quarter")){//每季度
                                            // 如果授信类型是数量
                                            if(currentQuantity>countQuota.getResidualQuantity()){
                                                return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每季度领取的最大数量");
                                            }
                                        }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("year")){//每年
                                            // 如果授信类型是数量
                                            if(currentQuantity>countQuota.getResidualQuantity()){
                                                return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每年领取的最大数量");
                                            }
                                        }
                                    }
                                }
                            }





                        }else{//权限组限制物料
                            if (authorityManageItem.getRestrictWay().equals(AuthorityManage.RestrictWay.category)) {//权限组限制物料 按分类
                                boolean flag = false;
                                String[] rangeArray = authorityManageItem.getMaterialId().split(",");
                                flag=Arrays.asList(rangeArray).contains(productDetailVO.getProductCategoryId().toString());
                                if(flag){
                                    //这个权限组包含要领取的物料
                                    //检查未归还的情况
                                    List<AuthorityMember> authorityMembers = authorityMemberService.list(new LambdaQueryWrapper<AuthorityMember>().eq(AuthorityMember::getAuthorityManageId, authorityManageItem.getId()));
                                    if (authorityManageItem.getCreditType().equals(AuthorityManage.CreditType.money)){
                                        //权限组按金额授信
                                        //权限组设置的金额未归还阈值
                                        BigDecimal moneyThreshold = authorityManageItem.getMoneyThreshold();
                                        //组员独享金额 只看着一个人的
                                        if (authorityManageItem.getCreditWay().equals(AuthorityManage.CreditWay.independent)){
                                            //该人未归还的信息  即正在用的
                                            List<UseInventoryUser> useInventoryUsers =  useInventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("creator",JwtUtils.getLoginUserId()).eq("cab_code",item.getCabCode()));
                                            //未归还的总金额
                                            BigDecimal total = new BigDecimal(0);
                                            for (UseInventoryUser useInventoryUser:useInventoryUsers){
                                                total=total.add(useInventoryUser.getTotal());
                                            }
                                            //如果该人的未归还的总金额大于权限组设置的金额未归还阈值 不让取
                                            if(total.compareTo(moneyThreshold)==1||total.compareTo(moneyThreshold)==0){
                                                return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"未归还金额已到达未归还金额阈值");
                                            }
                                        }else if(authorityManageItem.getCreditWay().equals(AuthorityManage.CreditWay.share)||authorityManageItem.getCreditWay().equals(AuthorityManage.CreditWay.unlimited)){
                                            //组员共享金额或者不限制金额 看全组的
                                            //未归还的总金额
                                            BigDecimal total = new BigDecimal(0);
                                            //该权限组的所有成员
                                            for (AuthorityMember authorityMember:authorityMembers){
                                                List<UseInventoryUser> useInventoryUsers =  useInventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("creator",authorityMember.getUserId()).eq("cab_code",item.getCabCode()));
                                                for (UseInventoryUser useInventoryUser:useInventoryUsers){
                                                    if(useInventoryUser.getTotal()==null){
                                                        total=total.add(new BigDecimal(0));
                                                    }else{
                                                        total=total.add(useInventoryUser.getTotal());
                                                    }
                                                }
                                            }
                                            if(total.compareTo(moneyThreshold)==1||total.compareTo(moneyThreshold)==0){
                                                return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"未归还金额已到达未归还金额阈值");
                                            }
                                        }
                                    }else{
                                        //权限组按数量授信
                                        //权限组设置的数量未归还阈值
                                        Integer quantityThreshold = authorityManageItem.getQuantityThreshold();
                                        //组员独享数量 只看这一个人的
                                        if (authorityManageItem.getCreditWay().equals(AuthorityManage.CreditWay.independentQuantity)){
                                            //该人未归还的信息  即正在用的
                                            List<UseInventoryUser> useInventoryUsers =  useInventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("creator",JwtUtils.getLoginUserId()).eq("cab_code",item.getCabCode()));
                                            //未归还的数量
                                            Integer qua = 0;
                                            for (UseInventoryUser useInventoryUser:useInventoryUsers){
                                                qua=qua+useInventoryUser.getQuantity();
                                            }
                                            //如果该人的未归还的总数量大于权限组设置的数量未归还阈值 不让取
                                            if(qua>=quantityThreshold){
                                                return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"未归还数量已到达未归还数量阈值");
                                            }
                                        }else if(authorityManageItem.getCreditWay().equals(AuthorityManage.CreditWay.shareQuantity)||authorityManageItem.getCreditWay().equals(AuthorityManage.CreditWay.unlimitedQuantity)){
                                            //组员共享数量或者不限制数量 看全组的
                                            //未归还的数量
                                            Integer qua = 0;
                                            //该权限组的所有成员
                                            for (AuthorityMember authorityMember:authorityMembers){
                                                List<UseInventoryUser> useInventoryUsers =  useInventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("creator",authorityMember.getUserId()).eq("cab_code",item.getCabCode()));
                                                for (UseInventoryUser useInventoryUser:useInventoryUsers){
                                                    qua=qua+useInventoryUser.getQuantity();
                                                }
                                            }
                                            if(qua>=quantityThreshold){
                                                return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"未归还数量已到达未归还数量阈值");
                                            }
                                        }
                                    }

                                    resetTime(authorityManageItem);//重置时间
                                    //检查当次领取是否超过限制数量或者金额
                                    CountQuota countQuota = null;
                                    if (authorityManageItem.getCreditWay().equals(AuthorityManage.CreditWay.shareQuantity)||authorityManageItem.getCreditWay().equals(AuthorityManage.CreditWay.share)){//共享金额或者共享数量
                                        countQuota = countQuotaService.getOne(new LambdaQueryWrapper<CountQuota>()
                                                .eq(CountQuota::getAuthorityManageId, authorityManageItem.getId())
                                                .eq(CountQuota::getSkuCode,item.getSkuCode()));
                                    }else{
                                        countQuota = countQuotaService.getOne(new LambdaQueryWrapper<CountQuota>()
                                                .eq(CountQuota::getAuthorityManageId, authorityManageItem.getId())
                                                .eq(CountQuota::getReceiverId, JwtUtils.getLoginUserId())
                                                .eq(CountQuota::getSkuCode,item.getSkuCode()));
                                    }
                                    if(countQuota!=null){
                                        //当前领取的金额
                                        BigDecimal currentAmount = productDetailVO.getMarketPrice().multiply(BigDecimal.valueOf(Math.abs(item.getQuantity())).multiply(BigDecimal.valueOf(item.getQuantityPackUnit())));

                                        //权限组的授信类型
                                        //金额
                                        if(authorityManageItem.getCreditType().getValue() == 0){
                                            //权限组的授信方式
                                            //组员共享领用金额
                                            if(authorityManageItem.getCreditWay().name().equals("share")){
                                                //额度评估周期
                                                if(authorityManageItem.getLineEvaluatePeriod().name().equals("day")){//每天
                                                    // 如果授信类型是金额
                                                    if(currentAmount.compareTo(countQuota.getBalance()) == 1){
                                                        return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每天领取的最大金额");
                                                    }
                                                }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("week")){//每周
                                                    // 如果授信类型是金额
                                                    if(currentAmount.compareTo(countQuota.getBalance()) == 1){
                                                        return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每周领取的最大金额");
                                                    }
                                                }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("month")){//每月
                                                    // 如果授信类型是金额
                                                    if(currentAmount.compareTo(countQuota.getBalance()) == 1){
                                                        return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每月领取的最大金额");
                                                    }
                                                }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("quarter")){//每季度
                                                    // 如果授信类型是金额
                                                    if(currentAmount.compareTo(countQuota.getBalance()) == 1){
                                                        return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每季度领取的最大金额");
                                                    }
                                                }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("year")){//每年
                                                    // 如果授信类型是金额
                                                    if(currentAmount.compareTo(countQuota.getBalance()) == 1){
                                                        return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每年领取的最大金额");
                                                    }
                                                }
                                            }else if(authorityManageItem.getCreditWay().name().equals("independent")){//组员独立授信领用金额
                                                //额度评估周期
                                                if(authorityManageItem.getLineEvaluatePeriod().name().equals("day")){//每天
                                                    // 如果授信类型是金额
                                                    if(currentAmount.compareTo(countQuota.getBalance()) == 1){
                                                        return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每天领取的最大金额");
                                                    }
                                                }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("week")){//每周
                                                    // 如果授信类型是金额
                                                    if(currentAmount.compareTo(countQuota.getBalance()) == 1){
                                                        return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每周领取的最大金额");
                                                    }
                                                }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("month")){//每月
                                                    // 如果授信类型是金额
                                                    if(currentAmount.compareTo(countQuota.getBalance()) == 1){
                                                        return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每月领取的最大金额");
                                                    }
                                                }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("quarter")){//每季度
                                                    // 如果授信类型是金额
                                                    if(currentAmount.compareTo(countQuota.getBalance()) == 1){
                                                        return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每季度领取的最大金额");
                                                    }
                                                }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("year")){//每年
                                                    // 如果授信类型是金额
                                                    if(currentAmount.compareTo(countQuota.getBalance()) == 1){
                                                        return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每年领取的最大金额");
                                                    }
                                                }
                                            }
                                        }else if(authorityManageItem.getCreditType().getValue() == 1){ //数量
                                            //当前领取的数量
                                            Integer currentQuantity = Math.abs(item.getQuantity())*item.getQuantityPackUnit();
                                            //权限组的授信方式
                                            if(authorityManageItem.getCreditWay().name().equals("shareQuantity")){ //组员共享领用数量
                                                //额度评估周期
                                                if(authorityManageItem.getLineEvaluatePeriod().name().equals("day")){//每天
                                                    // 如果授信类型是数量
                                                    if(currentQuantity>countQuota.getResidualQuantity()){
                                                        return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每天领取的最大数量");
                                                    }
                                                }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("week")){//每周
                                                    // 如果授信类型是数量
                                                    if(currentQuantity>countQuota.getResidualQuantity()){
                                                        return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每周领取的最大数量");
                                                    }
                                                }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("month")){//每月
                                                    // 如果授信类型是数量
                                                    if(currentQuantity>countQuota.getResidualQuantity()){
                                                        return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每月领取的最大数量");
                                                    }
                                                }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("quarter")){//每季度
                                                    // 如果授信类型是数量
                                                    if(currentQuantity>countQuota.getResidualQuantity()){
                                                        return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每季度领取的最大数量");
                                                    }
                                                }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("year")){//每年
                                                    // 如果授信类型是数量
                                                    if(currentQuantity>countQuota.getResidualQuantity()){
                                                        return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每年领取的最大数量");
                                                    }
                                                }
                                            }else if(authorityManageItem.getCreditWay().name().equals("independentQuantity")){//组员独立授信领用数量
                                                //额度评估周期
                                                if(authorityManageItem.getLineEvaluatePeriod().name().equals("day")){//每天
                                                    // 如果授信类型是数量
                                                    if(currentQuantity>countQuota.getResidualQuantity()){
                                                        return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每天领取的最大数量");
                                                    }
                                                }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("week")){//每周
                                                    // 如果授信类型是数量
                                                    if(currentQuantity>countQuota.getResidualQuantity()){
                                                        return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每周领取的最大数量");
                                                    }
                                                }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("month")){//每月
                                                    // 如果授信类型是数量
                                                    if(currentQuantity>countQuota.getResidualQuantity()){
                                                        return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每月领取的最大数量");
                                                    }
                                                }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("quarter")){//每季度
                                                    // 如果授信类型是数量
                                                    if(currentQuantity>countQuota.getResidualQuantity()){
                                                        return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每季度领取的最大数量");
                                                    }
                                                }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("year")){//每年
                                                    // 如果授信类型是数量
                                                    if(currentQuantity>countQuota.getResidualQuantity()){
                                                        return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每年领取的最大数量");
                                                    }
                                                }
                                            }
                                        }
                                    }



                                }else{
                                    //这个权限组不包含要领取的物料，看这个物料是否在这个柜子的别的权限组上，在不能领，不在，能领
                                    QueryWrapper<AuthorityManage> queryWrapper = new QueryWrapper<AuthorityManage>();
                                    queryWrapper.ne("id",id);
                                    queryWrapper.eq("status",0l);
                                    //queryWrapper.eq("cabinet_id",cabinets.get(0).getId());
                                    List<AuthorityManage> authorityManageList = authorityManageService.list(queryWrapper);
                                    if (authorityManageList.size()>0){
                                        authorityManageList.removeIf(authorityManage -> !authorityManage.getCabinetId().contains(cabinets.get(0).getId().toString()));
                                    }
                                    for(AuthorityManage authorityManage:authorityManageList){
                                        List<AuthorityMateriel> authorityMaterielList =  authorityMaterielService.list(new QueryWrapper<AuthorityMateriel>().eq("manage_id",authorityManage.getId()));
                                        for (AuthorityMateriel authorityMateriel:authorityMaterielList){
                                            if(authorityMateriel.getSkuCode().equals(item.getSkuCode())){
                                                return JsonResult.fail("您没有领取"+item.getSkuCode()+"的权限,请联系管理员");
                                            }
                                        }
                                    }
                                }
                            }else if(authorityManageItem.getRestrictWay().equals(AuthorityManage.RestrictWay.materiel)) {//权限组限制物料 按物料
                                Integer c = 0;
                                //权限组可领取的sku
                                List<AuthorityMateriel> authorityMaterielList = authorityMaterielService.list(new QueryWrapper<AuthorityMateriel>().eq("manage_id", authorityManageItem.getId()));
                                for (AuthorityMateriel authorityMateriel : authorityMaterielList) {
                                    if (productDetailVO.getSkuCode().equals(authorityMateriel.getSkuCode())) {
                                        c++;
                                    }
                                }
                                if (c != 0){
                                    //检查未归还的情况
                                    List<AuthorityMember> authorityMembers = authorityMemberService.list(new LambdaQueryWrapper<AuthorityMember>().eq(AuthorityMember::getAuthorityManageId, authorityManageItem.getId()));
                                    if (authorityManageItem.getCreditType().equals(AuthorityManage.CreditType.money)){
                                        //权限组按金额授信
                                        //权限组设置的金额未归还阈值
                                        BigDecimal moneyThreshold = authorityManageItem.getMoneyThreshold();
                                        //组员独享金额 只看着一个人的
                                        if (authorityManageItem.getCreditWay().equals(AuthorityManage.CreditWay.independent)){
                                            //该人未归还的信息  即正在用的
                                            List<UseInventoryUser> useInventoryUsers =  useInventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("creator",JwtUtils.getLoginUserId()).eq("cab_code",item.getCabCode()));
                                            //未归还的总金额
                                            BigDecimal total = new BigDecimal(0);
                                            for (UseInventoryUser useInventoryUser:useInventoryUsers){
                                                total=total.add(useInventoryUser.getTotal());
                                            }
                                            //如果该人的未归还的总金额大于权限组设置的金额未归还阈值 不让取
                                            if(total.compareTo(moneyThreshold)==1||total.compareTo(moneyThreshold)==0){
                                                return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"未归还金额已到达未归还金额阈值");
                                            }
                                        }else if(authorityManageItem.getCreditWay().equals(AuthorityManage.CreditWay.share)||authorityManageItem.getCreditWay().equals(AuthorityManage.CreditWay.unlimited)){
                                            //组员共享金额或者不限制金额 看全组的
                                            //未归还的总金额
                                            BigDecimal total = new BigDecimal(0);
                                            //该权限组的所有成员
                                            for (AuthorityMember authorityMember:authorityMembers){
                                                List<UseInventoryUser> useInventoryUsers =  useInventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("creator",authorityMember.getUserId()).eq("cab_code",item.getCabCode()));
                                                for (UseInventoryUser useInventoryUser:useInventoryUsers){
                                                    if(useInventoryUser.getTotal()==null){
                                                        total=total.add(new BigDecimal(0));
                                                    }else{
                                                        total=total.add(useInventoryUser.getTotal());
                                                    }
                                                }
                                            }
                                            if(total.compareTo(moneyThreshold)==1||total.compareTo(moneyThreshold)==0){
                                                return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"未归还金额已到达未归还金额阈值");
                                            }
                                        }
                                    }else{
                                        //权限组按数量授信
                                        //权限组设置的数量未归还阈值
                                        Integer quantityThreshold = authorityManageItem.getQuantityThreshold();
                                        //组员独享数量 只看这一个人的
                                        if (authorityManageItem.getCreditWay().equals(AuthorityManage.CreditWay.independentQuantity)){
                                            //该人未归还的信息  即正在用的
                                            List<UseInventoryUser> useInventoryUsers =  useInventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("creator",JwtUtils.getLoginUserId()).eq("cab_code",item.getCabCode()));
                                            //未归还的数量
                                            Integer qua = 0;
                                            for (UseInventoryUser useInventoryUser:useInventoryUsers){
                                                qua=qua+useInventoryUser.getQuantity();
                                            }
                                            //如果该人的未归还的总数量大于权限组设置的数量未归还阈值 不让取
                                            if(qua>=quantityThreshold){
                                                return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"未归还数量已到达未归还数量阈值");
                                            }
                                        }else if(authorityManageItem.getCreditWay().equals(AuthorityManage.CreditWay.shareQuantity)||authorityManageItem.getCreditWay().equals(AuthorityManage.CreditWay.unlimitedQuantity)){
                                            //组员共享数量或者不限制数量 看全组的
                                            //未归还的数量
                                            Integer qua = 0;
                                            //该权限组的所有成员
                                            for (AuthorityMember authorityMember:authorityMembers){
                                                List<UseInventoryUser> useInventoryUsers =  useInventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("creator",authorityMember.getUserId()).eq("cab_code",item.getCabCode()));
                                                for (UseInventoryUser useInventoryUser:useInventoryUsers){
                                                    qua=qua+useInventoryUser.getQuantity();
                                                }
                                            }
                                            if(qua>=quantityThreshold){
                                                return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"未归还数量已到达未归还数量阈值");
                                            }
                                        }
                                    }


                                    resetTime(authorityManageItem);//重置时间
                                    //检查当次领取是否超过限制数量或者金额
                                    CountQuota countQuota = null;
                                    if (authorityManageItem.getCreditWay().equals(AuthorityManage.CreditWay.shareQuantity)||authorityManageItem.getCreditWay().equals(AuthorityManage.CreditWay.share)){//共享金额或者共享数量
                                        countQuota = countQuotaService.getOne(new LambdaQueryWrapper<CountQuota>()
                                                .eq(CountQuota::getAuthorityManageId, authorityManageItem.getId())
                                                .eq(CountQuota::getSkuCode,item.getSkuCode()));
                                    }else{
                                        countQuota = countQuotaService.getOne(new LambdaQueryWrapper<CountQuota>()
                                                .eq(CountQuota::getAuthorityManageId, authorityManageItem.getId())
                                                .eq(CountQuota::getReceiverId, JwtUtils.getLoginUserId())
                                                .eq(CountQuota::getSkuCode,item.getSkuCode()));
                                    }
                                    if(countQuota!=null){
                                        //当前领取的金额
                                        BigDecimal currentAmount = productDetailVO.getMarketPrice().multiply(BigDecimal.valueOf(Math.abs(item.getQuantity())).multiply(BigDecimal.valueOf(item.getQuantityPackUnit())));

                                        //权限组的授信类型
                                        //金额
                                        if(authorityManageItem.getCreditType().getValue() == 0){
                                            //权限组的授信方式
                                            //组员共享领用金额
                                            if(authorityManageItem.getCreditWay().name().equals("share")){
                                                //额度评估周期
                                                if(authorityManageItem.getLineEvaluatePeriod().name().equals("day")){//每天
                                                    // 如果授信类型是金额
                                                    if(currentAmount.compareTo(countQuota.getBalance()) == 1){
                                                        return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每天领取的最大金额");
                                                    }
                                                }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("week")){//每周
                                                    // 如果授信类型是金额
                                                    if(currentAmount.compareTo(countQuota.getBalance()) == 1){
                                                        return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每周领取的最大金额");
                                                    }
                                                }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("month")){//每月
                                                    // 如果授信类型是金额
                                                    if(currentAmount.compareTo(countQuota.getBalance()) == 1){
                                                        return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每月领取的最大金额");
                                                    }
                                                }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("quarter")){//每季度
                                                    // 如果授信类型是金额
                                                    if(currentAmount.compareTo(countQuota.getBalance()) == 1){
                                                        return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每季度领取的最大金额");
                                                    }
                                                }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("year")){//每年
                                                    // 如果授信类型是金额
                                                    if(currentAmount.compareTo(countQuota.getBalance()) == 1){
                                                        return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每年领取的最大金额");
                                                    }
                                                }
                                            }else if(authorityManageItem.getCreditWay().name().equals("independent")){//组员独立授信领用金额
                                                //额度评估周期
                                                if(authorityManageItem.getLineEvaluatePeriod().name().equals("day")){//每天
                                                    // 如果授信类型是金额
                                                    if(currentAmount.compareTo(countQuota.getBalance()) == 1){
                                                        return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每天领取的最大金额");
                                                    }
                                                }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("week")){//每周
                                                    // 如果授信类型是金额
                                                    if(currentAmount.compareTo(countQuota.getBalance()) == 1){
                                                        return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每周领取的最大金额");
                                                    }
                                                }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("month")){//每月
                                                    // 如果授信类型是金额
                                                    if(currentAmount.compareTo(countQuota.getBalance()) == 1){
                                                        return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每月领取的最大金额");
                                                    }
                                                }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("quarter")){//每季度
                                                    // 如果授信类型是金额
                                                    if(currentAmount.compareTo(countQuota.getBalance()) == 1){
                                                        return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每季度领取的最大金额");
                                                    }
                                                }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("year")){//每年
                                                    // 如果授信类型是金额
                                                    if(currentAmount.compareTo(countQuota.getBalance()) == 1){
                                                        return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每年领取的最大金额");
                                                    }
                                                }
                                            }
                                        }else if(authorityManageItem.getCreditType().getValue() == 1){ //数量
                                            //当前领取的数量
                                            Integer currentQuantity = Math.abs(item.getQuantity())*item.getQuantityPackUnit();
                                            //权限组的授信方式
                                            if(authorityManageItem.getCreditWay().name().equals("shareQuantity")){ //组员共享领用数量
                                                //额度评估周期
                                                if(authorityManageItem.getLineEvaluatePeriod().name().equals("day")){//每天
                                                    // 如果授信类型是数量
                                                    if(currentQuantity>countQuota.getResidualQuantity()){
                                                        return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每天领取的最大数量");
                                                    }
                                                }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("week")){//每周
                                                    // 如果授信类型是数量
                                                    if(currentQuantity>countQuota.getResidualQuantity()){
                                                        return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每周领取的最大数量");
                                                    }
                                                }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("month")){//每月
                                                    // 如果授信类型是数量
                                                    if(currentQuantity>countQuota.getResidualQuantity()){
                                                        return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每月领取的最大数量");
                                                    }
                                                }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("quarter")){//每季度
                                                    // 如果授信类型是数量
                                                    if(currentQuantity>countQuota.getResidualQuantity()){
                                                        return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每季度领取的最大数量");
                                                    }
                                                }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("year")){//每年
                                                    // 如果授信类型是数量
                                                    if(currentQuantity>countQuota.getResidualQuantity()){
                                                        return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每年领取的最大数量");
                                                    }
                                                }
                                            }else if(authorityManageItem.getCreditWay().name().equals("independentQuantity")){//组员独立授信领用数量
                                                //额度评估周期
                                                if(authorityManageItem.getLineEvaluatePeriod().name().equals("day")){//每天
                                                    // 如果授信类型是数量
                                                    if(currentQuantity>countQuota.getResidualQuantity()){
                                                        return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每天领取的最大数量");
                                                    }
                                                }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("week")){//每周
                                                    // 如果授信类型是数量
                                                    if(currentQuantity>countQuota.getResidualQuantity()){
                                                        return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每周领取的最大数量");
                                                    }
                                                }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("month")){//每月
                                                    // 如果授信类型是数量
                                                    if(currentQuantity>countQuota.getResidualQuantity()){
                                                        return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每月领取的最大数量");
                                                    }
                                                }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("quarter")){//每季度
                                                    // 如果授信类型是数量
                                                    if(currentQuantity>countQuota.getResidualQuantity()){
                                                        return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每季度领取的最大数量");
                                                    }
                                                }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("year")){//每年
                                                    // 如果授信类型是数量
                                                    if(currentQuantity>countQuota.getResidualQuantity()){
                                                        return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每年领取的最大数量");
                                                    }
                                                }
                                            }
                                        }
                                    }


                                }else{
                                    //这个权限组不包含要领取的物料，看这个物料是否在这个柜子别的权限组上，在不能领，不在，能领
                                    QueryWrapper<AuthorityManage> queryWrapper = new QueryWrapper<AuthorityManage>();
                                    queryWrapper.ne("id",id);
                                    queryWrapper.eq("status",0l);
                                    //queryWrapper.eq("cabinet_id",cabinets.get(0).getId());
                                    List<AuthorityManage> authorityManageList = authorityManageService.list(queryWrapper);
                                    if (authorityManageList.size()>0){
                                        authorityManageList.removeIf(authorityManage -> !authorityManage.getCabinetId().contains(cabinets.get(0).getId().toString()));
                                    }
                                    for(AuthorityManage authorityManage:authorityManageList){
                                        List<AuthorityMateriel> authorityMaterielList1 =  authorityMaterielService.list(new QueryWrapper<AuthorityMateriel>().eq("manage_id",authorityManage.getId()));
                                        for (AuthorityMateriel authorityMateriel:authorityMaterielList1){
                                            if(authorityMateriel.getSkuCode().equals(item.getSkuCode())){
                                                return JsonResult.fail("您没有领取"+item.getSkuCode()+"的权限,请联系管理员");
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }else{
                        //当前登录人所在的权限组不在该柜子上
                        //没有加入柜子上权限组的物料可以领  加入了的不能领
                        for(AuthorityManage authorityManage:manageList){
                            if (authorityManage.getAstrictMaterial().equals(AuthorityManage.AstrictMaterial.noAstrict)){//权限组不限制物料  即 管控全部的物料
                                return JsonResult.fail("您没有领取"+item.getSkuCode()+"的权限,请联系管理员");
                            }else{//权限组限制物料
                                if (authorityManage.getRestrictWay().equals(AuthorityManage.RestrictWay.category)){//权限组限制物料 按分类
                                    boolean flag = false;
                                    String[] rangeArray = authorityManage.getMaterialId().split(",");
                                    flag=Arrays.asList(rangeArray).contains(productDetailVO.getProductCategoryId().toString());
                                    if(flag){
                                        return JsonResult.fail("您没有领取"+item.getSkuCode()+"的权限,请联系管理员");
                                    }
                                }else if(authorityManage.getRestrictWay().equals(AuthorityManage.RestrictWay.materiel)){//权限组限制物料 按分类
                                    Integer c = 0;
                                    //权限组可领取的sku
                                    List<AuthorityMateriel> authorityMaterielList = authorityMaterielService.list(new QueryWrapper<AuthorityMateriel>().eq("manage_id", authorityManage.getId()));
                                    for (AuthorityMateriel authorityMateriel : authorityMaterielList) {
                                        if (productDetailVO.getSkuCode().equals(authorityMateriel.getSkuCode())) {
                                            c++;
                                        }
                                    }
                                    if (c != 0){
                                        return JsonResult.fail("您没有领取"+item.getSkuCode()+"的权限,请联系管理员");
                                    }
                                }
                            }
                        }
                    }
                }else {
                    //当前登录人没有权限组
                    //没有加入柜子上权限组的物料可以领  加入了的不能领
                    for(AuthorityManage authorityManage:manageList){
                        if (authorityManage.getAstrictMaterial().equals(AuthorityManage.AstrictMaterial.noAstrict)){//权限组不限制物料  即 管控全部的物料
                            return JsonResult.fail("您没有领取该物料的权限,请联系管理员");
                        }else{//权限组限制物料
                            if (authorityManage.getRestrictWay().equals(AuthorityManage.RestrictWay.category)){//权限组限制物料 按分类
                                boolean flag = false;
                                String[] rangeArray = authorityManage.getMaterialId().split(",");
                                flag=Arrays.asList(rangeArray).contains(productDetailVO.getProductCategoryId().toString());
                                if(flag){
                                    return JsonResult.fail("您没有领取"+item.getSkuCode()+"的权限,请联系管理员");
                                }
                            }else if(authorityManage.getRestrictWay().equals(AuthorityManage.RestrictWay.materiel)){//权限组限制物料 按分类
                                Integer c = 0;
                                //权限组可领取的sku
                                List<AuthorityMateriel> authorityMaterielList = authorityMaterielService.list(new QueryWrapper<AuthorityMateriel>().eq("manage_id", authorityManage.getId()));
                                for (AuthorityMateriel authorityMateriel : authorityMaterielList) {
                                    if (productDetailVO.getSkuCode().equals(authorityMateriel.getSkuCode())) {
                                        c++;
                                    }
                                }
                                if (c != 0){
                                    return JsonResult.fail("您没有领取"+item.getSkuCode()+"的权限,请联系管理员");
                                }
                            }
                        }
                    }
                }
            }/*else{
                //正在领料的柜子上没有权限组
                //这个柜子上的谁都可以领
            }*/
        }






        //上面相当于先把要领的所有物料的 不能领的情况排除
        //再看具体领取限制情况  只有在该权限组的人领取在该权限组的物料才需要
        for(CellInventoryInoutDetailForm item:list){
            //要领取的物料
            ProductDetailVO productDetailVO = productDetailService.getProductDetailBySkuCode(item.getSkuCode());
            if (manageList.size()>0){//正在领料的柜子上有权限组
                if(authorityMemberList.size()>0){
                    //当前登录人有权限组
                    //查看当前登录人所在的权限组是否在该柜子上
                    Integer a =0;
                    Long id = null;
                    loop : for(AuthorityManage authorityManageItem:manageList){
                        for(AuthorityMember authorityMember:authorityMemberList){
                            if (authorityManageItem.getId()==authorityMember.getAuthorityManageId()){
                                a++;
                                id=authorityManageItem.getId();
                                break loop;
                            }
                        }
                    }
                    if (a>0) {
                        //当前登录人所在的权限组在该柜子上
                        //包含 看权限组怎么限制的  来领取
                        AuthorityManage  authorityManageItem = authorityManageService.getById(id);
                        if (authorityManageItem.getAstrictMaterial().equals(AuthorityManage.AstrictMaterial.noAstrict)){//权限组不限制物料  即 管控全部的物料
                            //领取时  如果是新加的物料 权限组物料表和统计表都要加上
                            List<AuthorityMateriel> authorityMaterielList =  authorityMaterielService.list(new QueryWrapper<AuthorityMateriel>().eq("manage_id",authorityManageItem.getId()));
                            Integer b = 0;
                            for (AuthorityMateriel authorityMateriel:authorityMaterielList){
                                if (authorityMateriel.getSkuCode().equals(item.getSkuCode())){
                                    b++;
                                }
                            }
                            if (b<1){
                                AuthorityMateriel authorityMateriel = new AuthorityMateriel();
                                CopyOptions copyOptions = CopyOptions.create()
                                        .setEditable(AuthorityMateriel.class)
                                        .setIgnoreError(true)
                                        .setIgnoreNullValue(true);
                                BeanUtil.copyProperties(authorityMaterielList.get(0), authorityMateriel, copyOptions);
                                authorityMateriel.setSkuCode(item.getSkuCode());
                                if (authorityManageItem.getCreditType().equals(AuthorityManage.CreditType.money)){
                                    authorityMateriel.setAmount(authorityManageItem.getLineOfCredit());
                                }else {
                                    authorityMateriel.setNumber(authorityManageItem.getAuthorizedQuantity());
                                }
                                authorityMaterielService.save(authorityMateriel);
                                List<AuthorityMember> authorityMembers = authorityMemberService.list(new QueryWrapper<AuthorityMember>().eq("authority_manage_id",authorityManageItem.getId()));
                                List<CountQuota> countQuotaList = countQuotaService.list(new QueryWrapper<CountQuota>().eq("authority_manage_id",authorityManageItem.getId()));
                                CountQuota countQuota = countQuotaList.get(0);

                                if (authorityManageItem.getCreditWay().equals(AuthorityManage.CreditWay.shareQuantity)||authorityManageItem.getCreditWay().equals(AuthorityManage.CreditWay.share)){//共享金额或者共享数量
                                    CountQuota countQuota1 = new CountQuota();
                                    CopyOptions copyOptions1 = CopyOptions.create()
                                            .setEditable(CountQuota.class)
                                            .setIgnoreError(true)
                                            .setIgnoreNullValue(true);
                                    BeanUtil.copyProperties(countQuota, countQuota1, copyOptions1);
                                    countQuota1.setSkuCode(item.getSkuCode());
                                    countQuotaService.save(countQuota1);
                                }else{
                                    for (AuthorityMember authorityMember:authorityMembers){
                                        CountQuota countQuota1 = new CountQuota();
                                        CopyOptions copyOptions1 = CopyOptions.create()
                                                .setEditable(CountQuota.class)
                                                .setIgnoreError(true)
                                                .setIgnoreNullValue(true);
                                        BeanUtil.copyProperties(countQuota, countQuota1, copyOptions1);
                                        countQuota1.setSkuCode(item.getSkuCode());
                                        countQuota1.setReceiverId(authorityMember.getUserId());
                                        countQuota1.setReceiverName(authorityMember.getUserName());
                                        if(authorityManageItem.getCreditWay().equals(AuthorityManage.CreditWay.independent)){//组员独立金额
                                            countQuota1.setLineOfCredit(authorityManageItem.getLineOfCredit());
                                            countQuota1.setBalance(authorityManageItem.getLineOfCredit());
                                        }
                                        if(authorityManageItem.getCreditWay().equals(AuthorityManage.CreditWay.independentQuantity)){//组员独立数量
                                            countQuota1.setAuthorizedQuantity(authorityManageItem.getAuthorizedQuantity());
                                            countQuota1.setResidualQuantity(authorityManageItem.getAuthorizedQuantity());
                                        }
                                        countQuotaService.save(countQuota1);
                                    }
                                }
                                countNew(authorityManageItem,item,productDetailVO);//修改count表
                            }
                        }else{//权限组限制物料
                            if (authorityManageItem.getRestrictWay().equals(AuthorityManage.RestrictWay.category)) {//权限组限制物料 按分类
                                boolean flag = false;
                                String[] rangeArray = authorityManageItem.getMaterialId().split(",");
                                flag=Arrays.asList(rangeArray).contains(productDetailVO.getProductCategoryId().toString());
                                if(flag){
                                    //领取时  如果是新加的物料 权限组物料表和统计表都要加上
                                    List<AuthorityMateriel> authorityMaterielList =  authorityMaterielService.list(new QueryWrapper<AuthorityMateriel>().eq("manage_id",authorityManageItem.getId()));
                                    Integer b = 0;
                                    for (AuthorityMateriel authorityMateriel:authorityMaterielList){
                                        if (authorityMateriel.getSkuCode().equals(item.getSkuCode())){
                                            b++;
                                        }
                                    }
                                    if (b<1){
                                        AuthorityMateriel authorityMateriel = new AuthorityMateriel();
                                        CopyOptions copyOptions = CopyOptions.create()
                                                .setEditable(AuthorityMateriel.class)
                                                .setIgnoreError(true)
                                                .setIgnoreNullValue(true);
                                        BeanUtil.copyProperties(authorityMaterielList.get(0), authorityMateriel, copyOptions);
                                        authorityMateriel.setSkuCode(item.getSkuCode());
                                        if (authorityManageItem.getCreditType().equals(AuthorityManage.CreditType.money)){
                                            authorityMateriel.setAmount(authorityManageItem.getLineOfCredit());
                                        }else {
                                            authorityMateriel.setNumber(authorityManageItem.getAuthorizedQuantity());
                                        }
                                        authorityMaterielService.save(authorityMateriel);
                                        List<AuthorityMember> authorityMembers = authorityMemberService.list(new QueryWrapper<AuthorityMember>().eq("authority_manage_id",authorityManageItem.getId()));
                                        List<CountQuota> countQuotaList = countQuotaService.list(new QueryWrapper<CountQuota>().eq("authority_manage_id",authorityManageItem.getId()));
                                        CountQuota countQuota = countQuotaList.get(0);
                                        if (authorityManageItem.getCreditWay().equals(AuthorityManage.CreditWay.shareQuantity)||authorityManageItem.getCreditWay().equals(AuthorityManage.CreditWay.share)){//共享金额或者共享数量
                                            CountQuota countQuota1 = new CountQuota();
                                            CopyOptions copyOptions1 = CopyOptions.create()
                                                    .setEditable(CountQuota.class)
                                                    .setIgnoreError(true)
                                                    .setIgnoreNullValue(true);
                                            BeanUtil.copyProperties(countQuota, countQuota1, copyOptions1);
                                            countQuota1.setSkuCode(item.getSkuCode());
                                            countQuotaService.save(countQuota1);
                                        }else{
                                            for (AuthorityMember authorityMember:authorityMembers){
                                                CountQuota countQuota1 = new CountQuota();
                                                CopyOptions copyOptions1 = CopyOptions.create()
                                                        .setEditable(CountQuota.class)
                                                        .setIgnoreError(true)
                                                        .setIgnoreNullValue(true);
                                                BeanUtil.copyProperties(countQuota, countQuota1, copyOptions1);
                                                countQuota1.setSkuCode(item.getSkuCode());
                                                countQuota1.setReceiverId(authorityMember.getUserId());
                                                countQuota1.setReceiverName(authorityMember.getUserName());
                                                if(authorityManageItem.getCreditWay().equals(AuthorityManage.CreditWay.independent)){//组员独立金额
                                                    countQuota1.setLineOfCredit(authorityManageItem.getLineOfCredit());
                                                    countQuota1.setBalance(authorityManageItem.getLineOfCredit());
                                                }
                                                if(authorityManageItem.getCreditWay().equals(AuthorityManage.CreditWay.independentQuantity)){//组员独立数量
                                                    countQuota1.setAuthorizedQuantity(authorityManageItem.getAuthorizedQuantity());
                                                    countQuota1.setResidualQuantity(authorityManageItem.getAuthorizedQuantity());
                                                }
                                                countQuotaService.save(countQuota1);
                                            }
                                        }
                                    }
                                    countNew(authorityManageItem,item,productDetailVO);//修改count表
                                }
                            }else if(authorityManageItem.getRestrictWay().equals(AuthorityManage.RestrictWay.materiel)) {//权限组限制物料 按物料
                                Integer c = 0;
                                //权限组可领取的sku
                                List<AuthorityMateriel> authorityMaterielList = authorityMaterielService.list(new QueryWrapper<AuthorityMateriel>().eq("manage_id", authorityManageItem.getId()));
                                for (AuthorityMateriel authorityMateriel : authorityMaterielList) {
                                    if (productDetailVO.getSkuCode().equals(authorityMateriel.getSkuCode())) {
                                        c++;
                                    }
                                }
                                if (c != 0){
                                    countNew(authorityManageItem,item,productDetailVO);//修改count表
                                }
                            }
                        }
                    }
                }
            }
        }

        return JsonResult.success();
    }

    @Override
    public JsonResult<String> sendTest(String mailTo) {
        try {
//            InetAddress address = InetAddress.getLocalHost();
            HashMap map = mailInfo.queryInfo();
            String userName = map.get("send_account").toString();
            String password = map.get("email_password").toString();
            String host = map.get("smtp_server").toString();
            String port = map.get("port").toString();
            String ssl = map.get("is_ssl").toString();

//            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
//            mimeMessage.setFrom(new InternetAddress(mailInfo.queryInfo().get("send_account").toString()));
//            mimeMessage.addRecipient(Message.RecipientType.TO,
//                    new InternetAddress(mailTo));
//            mimeMessage.setSubject("主题：缺货告警提醒");
            StringBuffer content = new StringBuffer();
            content.append("<div style='font-size: 18px;min-height: 180px;height: auto;min-height:350px;background-color: #f5f5f7;box-shadow: 0 0 10px 3px #0000001a;border-radius: 20px;box-sizing: border-box;padding:30px;margin: 20px;'>");
            content.append("<div style='text-align: left;min-height: 180px; margin: 10px 0;height: auto; padding-left: 2em;'>");
            content.append("<p>主柜编号为ZG001。</p>");
            content.append("<p>柜子编号为ZG001-G1。</p>");
            content.append("<p>物料编码为SKU-012。</p>");
            content.append("<p>告警设置数量为12（现剩余库存数量为10，缺货数量为2）。</p>");
            content.append("</div>");
            content.append("</div>");
            //mimeMessage.setContent( content.toString(), "text/html;charset=UTF-8");
            //javaMailSender.send(mimeMessage);
            senderConfig.sendMail(userName,password,host,ssl, Integer.valueOf(port),mailTo,"主题：缺货告警提醒",content.toString());
            return JsonResult.success("success");
        } catch (MessagingException e) {
            log.error("发送邮件失败:" + e.getMessage());
            return JsonResult.fail("fail");
        } catch (Exception e) {
            log.error("send mail fail", e);
            return JsonResult.fail("fail");
        }
    }


    /*@Transactional
    @Override
    public JsonResult verifyPermissions(List<CellInventoryInoutDetailForm> list){
        for(CellInventoryInoutDetailForm item:list){
            //根据cabCode查询主柜
            List<Cabinet> cabinetCodes = cabinetService.list(new LambdaQueryWrapper<Cabinet>().eq(Cabinet::getCode, item.getCabCode()));
            List<Cabinet> cabinets = cabinetService.list(new LambdaQueryWrapper<Cabinet>().eq(Cabinet::getCabCode, cabinetCodes.get(0).getBelongCabinet()));
            //查找该柜子上的启用状态的权限组
            List<AuthorityManage> manageList = authorityManageService.list(new LambdaQueryWrapper<AuthorityManage>()
                    .eq(AuthorityManage::getCabinetId, cabinets.get(0).getId()).eq(AuthorityManage::getStatus,0l));
            //获得当前登录人所在的权限组
            //List<AuthorityMember> authorityMemberList = authorityMemberService.list(new LambdaQueryWrapper<AuthorityMember>().eq(AuthorityMember::getUserId, JwtUtils.getLoginUserId()));
            //要领取的物料
            //ProductDetailVO productDetailVO = productDetailService.getProductDetailBySkuCode(item.getSkuCode());

            Boolean isExist = false;
            Boolean isDisabled = false;

            if(manageList.size()>0){//柜子有权限组
               *//* if (authorityMemberList.size()>0){
                    //当前登录人有权限组
                }else{
                    //当前登录人不在任何权限组
                    //没有加入柜子上权限组的物料可以领  加入了的不能领
                }*//*
                for(AuthorityManage authorityManageItem:manageList){
                    //状态正常的 启用状态的
                    if(authorityManageItem.getStatus() == 0){
                        isDisabled = true;
                        //权限组是否被禁用
                        if(isDisabled){
                            //该权限组的所有成员
                            List<AuthorityMember> authorityMemberList = authorityMemberService.list(new LambdaQueryWrapper<AuthorityMember>().eq(AuthorityMember::getAuthorityManageId, authorityManageItem.getId()));
                            //该人是否在权限组
                            List<AuthorityMember> memberList = authorityMemberList.stream().filter(s -> s.getUserId().equals(JwtUtils.getLoginUserId())).collect(Collectors.toList());
                            if(memberList.size()>0){//当前用户在该权限组
                                isExist = true;
                            }
                            //判断当前领取人是否有权限
                            if(isExist){
                                //要判断未归还的阈值
                                if (authorityManageItem.getCreditType().equals(AuthorityManage.CreditType.money)){
                                    //权限组按金额授信
                                    //权限组设置的金额未归还阈值
                                    BigDecimal moneyThreshold = authorityManageItem.getMoneyThreshold();
                                    //组员独享金额 只看着一个人的
                                    if (authorityManageItem.getCreditWay().equals(AuthorityManage.CreditWay.independent)){
                                        //该人未归还的信息  即正在用的
                                        List<UseInventoryUser> useInventoryUsers =  useInventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("creator",item.getCreator()).eq("cab_code",item.getCabCode()));
                                        //未归还的总金额
                                        BigDecimal total = new BigDecimal(0);
                                        for (UseInventoryUser useInventoryUser:useInventoryUsers){
                                            total.add(useInventoryUser.getTotal());
                                        }
                                        //如果该人的未归还的总金额大于权限组设置的金额未归还阈值 不让取
                                        if(total.compareTo(moneyThreshold)==1){
                                            return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"未归还金额大于未归还金额阈值");
                                        }
                                    }else if(authorityManageItem.getCreditWay().equals(AuthorityManage.CreditWay.share)||authorityManageItem.getCreditWay().equals(AuthorityManage.CreditWay.unlimited)){
                                        //组员共享金额或者不限制金额 看全组的
                                        //未归还的总金额
                                        BigDecimal total = new BigDecimal(0);
                                        //该权限组的所有成员
                                        for (AuthorityMember authorityMember:authorityMemberList){
                                            List<UseInventoryUser> useInventoryUsers =  useInventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("creator",authorityMember.getUserId()).eq("cab_code",item.getCabCode()));
                                            for (UseInventoryUser useInventoryUser:useInventoryUsers){
                                                if(useInventoryUser.getTotal()==null){
                                                    total.add(new BigDecimal(0));
                                                }else{
                                                    total.add(useInventoryUser.getTotal());
                                                }
                                            }
                                        }
                                        if(total.compareTo(moneyThreshold)==1){
                                            return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"未归还金额大于未归还金额阈值");
                                        }
                                    }
                                }else{
                                    //权限组按数量授信
                                    //权限组设置的数量未归还阈值
                                    Integer quantityThreshold = authorityManageItem.getQuantityThreshold();
                                    //组员独享数量 只看这一个人的
                                    if (authorityManageItem.getCreditWay().equals(AuthorityManage.CreditWay.independentQuantity)){
                                        //该人未归还的信息  即正在用的
                                        List<UseInventoryUser> useInventoryUsers =  useInventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("creator",item.getCreator()).eq("cab_code",item.getCabCode()));
                                        //未归还的数量
                                        Integer qua = 0;
                                        for (UseInventoryUser useInventoryUser:useInventoryUsers){
                                            //qua=qua+useInventoryUser.getQuantityPack();
                                            qua=qua+useInventoryUser.getQuantity();
                                        }
                                        //如果该人的未归还的总数量大于权限组设置的数量未归还阈值 不让取
                                        if(qua>quantityThreshold){
                                            return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"未归还数量大于未归还数量阈值");
                                        }
                                    }else if(authorityManageItem.getCreditWay().equals(AuthorityManage.CreditWay.shareQuantity)||authorityManageItem.getCreditWay().equals(AuthorityManage.CreditWay.unlimitedQuantity)){
                                        //组员共享数量或者不限制数量 看全组的
                                        //未归还的数量
                                        Integer qua = 0;
                                        //该权限组的所有成员
                                        for (AuthorityMember authorityMember:authorityMemberList){
                                            List<UseInventoryUser> useInventoryUsers =  useInventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("creator",authorityMember.getUserId()).eq("cab_code",item.getCabCode()));
                                            for (UseInventoryUser useInventoryUser:useInventoryUsers){
                                                //qua=qua+useInventoryUser.getQuantityPack();
                                                qua=qua+useInventoryUser.getQuantity();
                                            }
                                        }
                                        if(qua>quantityThreshold){
                                            return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"未归还数量大于未归还数量阈值");
                                        }
                                    }
                                }



                                //要领取的物料
                                ProductDetailSelf productDetail = productDetailSelfService.getOne(new LambdaQueryWrapper<ProductDetailSelf>().eq(ProductDetailSelf::getSkuCode, item.getSkuCode()));
                                //权限组的领取范围

                                String[] rangeArray = authorityManageItem.getMaterialId().split(",");
                                //限制物料
                                if(authorityManageItem.getAstrictMaterial().name().equals("astrict")){
                                    boolean flag = true;
                                    //限制方式按分类
                                    if(authorityManageItem.getRestrictWay().equals(AuthorityManage.RestrictWay.category)){
                                        if (productDetail.getProductCategoryId()==null){
                                            flag=false;
                                        }else{
                                            flag=Arrays.asList(rangeArray).contains(productDetail.getProductCategoryId().toString());
                                        }
                                        if(!flag){
                                            return JsonResult.fail("该产品不在可领物料分类范围内！！！");
                                        }
                                        if(flag){
                                            //领取时 权限组是限制方式按分类  现在领取的这个物料是该分类下新添加的  之前新建该权限组时没有该物料   权限组物料表和统计表都要加上
                                            List<AuthorityMateriel> authorityMaterielList =  authorityMaterielService.list(new QueryWrapper<AuthorityMateriel>().eq("manage_id",authorityManageItem.getId()));
                                            Integer a = 0;
                                            for (AuthorityMateriel authorityMateriel:authorityMaterielList){
                                                if (authorityMateriel.getSkuCode().equals(item.getSkuCode())){
                                                    a++;
                                                }
                                            }
                                            if (a<1){
                                                AuthorityMateriel authorityMateriel = new AuthorityMateriel();
                                                CopyOptions copyOptions = CopyOptions.create()
                                                        .setEditable(AuthorityMateriel.class)
                                                        .setIgnoreError(true)
                                                        .setIgnoreNullValue(true);
                                                BeanUtil.copyProperties(authorityMaterielList.get(0), authorityMateriel, copyOptions);
                                                authorityMateriel.setSkuCode(item.getSkuCode());
                                                if (authorityManageItem.getCreditType().equals(AuthorityManage.CreditType.money)){
                                                    authorityMateriel.setAmount(authorityManageItem.getLineOfCredit());
                                                }else {
                                                    authorityMateriel.setNumber(authorityManageItem.getAuthorizedQuantity());
                                                }
                                                authorityMaterielService.save(authorityMateriel);
                                                List<AuthorityMember> authorityMembers = authorityMemberService.list(new QueryWrapper<AuthorityMember>().eq("authority_manage_id",authorityManageItem.getId()));
                                                //CountQuota countQuota = countQuotaService.getOne(new QueryWrapper<CountQuota>().eq("authority_manage_id",authorityManageItem.getId()));
                                                List<CountQuota> countQuotaList = countQuotaService.list(new QueryWrapper<CountQuota>().eq("authority_manage_id",authorityManageItem.getId()));
                                                CountQuota countQuota = countQuotaList.get(0);
                                                for (AuthorityMember authorityMember:authorityMembers){
                                                    CountQuota countQuota1 = new CountQuota();
                                                    CopyOptions copyOptions1 = CopyOptions.create()
                                                            .setEditable(CountQuota.class)
                                                            .setIgnoreError(true)
                                                            .setIgnoreNullValue(true);
                                                    BeanUtil.copyProperties(countQuota, countQuota1, copyOptions1);
                                                    countQuota1.setSkuCode(item.getSkuCode());
                                                    countQuota1.setReceiverId(authorityMember.getUserId());
                                                    countQuota1.setReceiverName(authorityMember.getUserName());
                                                    if(authorityManageItem.getCreditWay().equals(AuthorityManage.CreditWay.independent)){//组员独立金额
                                                        countQuota1.setLineOfCredit(authorityManageItem.getLineOfCredit());
                                                        countQuota1.setBalance(authorityManageItem.getLineOfCredit());
                                                    }
                                                    if(authorityManageItem.getCreditWay().equals(AuthorityManage.CreditWay.independentQuantity)){//组员独立数量
                                                        countQuota1.setAuthorizedQuantity(authorityManageItem.getAuthorizedQuantity());
                                                        countQuota1.setResidualQuantity(authorityManageItem.getAuthorizedQuantity());
                                                    }
                                                    countQuotaService.save(countQuota1);
                                                }
                                            }

                                        }
                                    }else if(authorityManageItem.getRestrictWay().equals(AuthorityManage.RestrictWay.materiel)){
                                        //限制方式按物料
                                        Integer a = 0;
                                        //权限组可领取的sku
                                        List<AuthorityMateriel> authorityMaterielList =  authorityMaterielService.list(new QueryWrapper<AuthorityMateriel>().eq("manage_id",authorityManageItem.getId()));
                                        for (AuthorityMateriel authorityMateriel:authorityMaterielList){
                                            if(item.getSkuCode().equals(authorityMateriel.getSkuCode())){
                                                a++;
                                            }
                                        }
                                        if (a==0){
                                            return JsonResult.fail("该产品不在可领物料范围内！！！");
                                        }
                                    }

                                }


                                //同一个权限组下的所有人的所有的物料 重置更新时间是一样的
                                List<CountQuota> countQuotaList1 = countQuotaService.list(new LambdaQueryWrapper<CountQuota>()
                                        .eq(CountQuota::getAuthorityManageId, authorityManageItem.getId()));
                                if(countQuotaList1.size()>0){
                                    LocalDateTime now = LocalDateTime.of(LocalDate.now(), LocalTime.now());
                                    //如果现在的时间也就是领取时间是在重置更新时间之后，就去将重置更新时间更新为下一次  将剩余可领的金额/数量重置
                                    if (now.isAfter(countQuotaList1.get(0).getResetTime())){
                                        for (CountQuota countQuota1:countQuotaList1){
                                            //额度评估周期
                                            if(authorityManageItem.getLineEvaluatePeriod().equals(AuthorityManage.LineEvaluatePeriod.day)){//每天
                                                countQuota1.setResetTime(LocalDateTime.of(LocalDate.now().plusDays(1), LocalTime.MIN));
                                                if (countQuota1.getCreditType().equals(CountQuota.CreditType.money)){
                                                    countQuota1.setBalance(countQuota1.getLineOfCredit());
                                                }else if(countQuota1.getCreditType(). equals(CountQuota.CreditType.quantity)){
                                                    countQuota1.setResidualQuantity(countQuota1.getAuthorizedQuantity());
                                                }
                                            }else if(authorityManageItem.getLineEvaluatePeriod().equals(AuthorityManage.LineEvaluatePeriod.week)){//每周
                                                countQuota1.setResetTime(LocalDateTime.of(LocalDate.now().plusWeeks(1), LocalTime.MIN));
                                                if (countQuota1.getCreditType().equals(CountQuota.CreditType.money)){
                                                    countQuota1.setBalance(countQuota1.getLineOfCredit());
                                                }else if(countQuota1.getCreditType().equals(CountQuota.CreditType.quantity)){
                                                    countQuota1.setResidualQuantity(countQuota1.getAuthorizedQuantity());
                                                }
                                            }else if(authorityManageItem.getLineEvaluatePeriod().equals(AuthorityManage.LineEvaluatePeriod.month)){//每月
                                                countQuota1.setResetTime(LocalDateTime.of(LocalDate.now().plusMonths(1), LocalTime.MIN));
                                                if (countQuota1.getCreditType().equals(CountQuota.CreditType.money)){
                                                    countQuota1.setBalance(countQuota1.getLineOfCredit());
                                                }else if(countQuota1.getCreditType().equals(CountQuota.CreditType.quantity)){
                                                    countQuota1.setResidualQuantity(countQuota1.getAuthorizedQuantity());
                                                }
                                            }else if(authorityManageItem.getLineEvaluatePeriod().equals(AuthorityManage.LineEvaluatePeriod.quarter)){//每季度
                                                countQuota1.setResetTime(LocalDateTime.of(LocalDate.now().plusMonths(3), LocalTime.MIN));
                                                if (countQuota1.getCreditType().equals(CountQuota.CreditType.money)){
                                                    countQuota1.setBalance(countQuota1.getLineOfCredit());
                                                }else if(countQuota1.getCreditType().equals(CountQuota.CreditType.quantity)){
                                                    countQuota1.setResidualQuantity(countQuota1.getAuthorizedQuantity());
                                                }
                                            }else if(authorityManageItem.getLineEvaluatePeriod().equals(AuthorityManage.LineEvaluatePeriod.year)){//每年
                                                countQuota1.setResetTime(LocalDateTime.of(LocalDate.now().plusYears(1), LocalTime.MIN));
                                                if (countQuota1.getCreditType().equals(CountQuota.CreditType.money)){
                                                    countQuota1.setBalance(countQuota1.getLineOfCredit());
                                                }else if(countQuota1.getCreditType().equals(CountQuota.CreditType.quantity)){
                                                    countQuota1.setResidualQuantity(countQuota1.getAuthorizedQuantity());
                                                }
                                            }
                                            countQuotaService.updateById(countQuota1);
                                        }
                                    }
                                }

                                CountQuota countQuota = countQuotaService.getOne(new LambdaQueryWrapper<CountQuota>()
                                        .eq(CountQuota::getAuthorityManageId, authorityManageItem.getId())
                                        .eq(CountQuota::getReceiverId, JwtUtils.getLoginUserId())
                                        .eq(CountQuota::getSkuCode,item.getSkuCode()));
                                if(countQuota!=null){
                                    //当前领取的金额
                                    BigDecimal currentAmount = productDetail.getMarketPrice().multiply(BigDecimal.valueOf(Math.abs(item.getQuantity())).multiply(BigDecimal.valueOf(item.getQuantityPackUnit())));
                                    //额度
                                    //BigDecimal usableAmount = authorityManageItem.getLineOfCredit();
                                    BigDecimal usableAmount =  authorityMaterielService.getOne(new QueryWrapper<AuthorityMateriel>().eq("manage_id",authorityManageItem.getId()).eq("sku_code",item.getSkuCode())).getAmount();

                                    //权限组的授信类型
                                    //金额
                                    if(authorityManageItem.getCreditType().getValue() == 0){
                                        //剩余可领金额
                                        BigDecimal surplusAmount = countQuota.getBalance().subtract(currentAmount);
                                        //权限组的授信方式
                                        //组员共享领用金额
                                        if(authorityManageItem.getCreditWay().name().equals("share")){
                                            //额度评估周期
                                            if(authorityManageItem.getLineEvaluatePeriod().name().equals("day")){//每天
                                                // 如果授信类型是金额
                                                if(currentAmount.compareTo(countQuota.getBalance()) == 1){
                                                    return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每天领取的最大金额");
                                                }
                                                //异步统计
                                                addReceiveRecord(authorityManageItem.getId(),authorityManageItem.getLineEvaluatePeriod().name(),item.getSkuCode()
                                                        ,productDetail.getMarketPrice(),item.getQuantity(),JwtUtils.getLoginUserId()
                                                        ,authorityManageItem.getCreditWay().name(),usableAmount,currentAmount);
                                            }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("week")){//每周
                                                // 如果授信类型是金额
                                                if(currentAmount.compareTo(countQuota.getBalance()) == 1){
                                                    return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每周领取的最大金额");
                                                }
                                                //异步统计
                                                addReceiveRecord(authorityManageItem.getId(),authorityManageItem.getLineEvaluatePeriod().name(),item.getSkuCode()
                                                        ,productDetail.getMarketPrice(),item.getQuantity(),JwtUtils.getLoginUserId()
                                                        ,authorityManageItem.getCreditWay().name(),usableAmount,currentAmount);
                                            }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("month")){//每月
                                                // 如果授信类型是金额
                                                if(currentAmount.compareTo(countQuota.getBalance()) == 1){
                                                    return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每月领取的最大金额");
                                                }
                                                //异步统计
                                                addReceiveRecord(authorityManageItem.getId(),authorityManageItem.getLineEvaluatePeriod().name(),item.getSkuCode()
                                                        ,productDetail.getMarketPrice(),item.getQuantity(),JwtUtils.getLoginUserId()
                                                        ,authorityManageItem.getCreditWay().name(),usableAmount,currentAmount);
                                            }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("quarter")){//每季度
                                                // 如果授信类型是金额
                                                if(currentAmount.compareTo(countQuota.getBalance()) == 1){
                                                    return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每季度领取的最大金额");
                                                }
                                                //异步统计
                                                addReceiveRecord(authorityManageItem.getId(),authorityManageItem.getLineEvaluatePeriod().name(),item.getSkuCode()
                                                        ,productDetail.getMarketPrice(),item.getQuantity(),JwtUtils.getLoginUserId()
                                                        ,authorityManageItem.getCreditWay().name(),usableAmount,currentAmount);
                                            }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("year")){//每年
                                                // 如果授信类型是金额
                                                if(currentAmount.compareTo(countQuota.getBalance()) == 1){
                                                    return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每年领取的最大金额");
                                                }
                                                //异步统计
                                                addReceiveRecord(authorityManageItem.getId(),authorityManageItem.getLineEvaluatePeriod().name(),item.getSkuCode()
                                                        ,productDetail.getMarketPrice(),item.getQuantity(),JwtUtils.getLoginUserId()
                                                        ,authorityManageItem.getCreditWay().name(),usableAmount,currentAmount);
                                            }
                                            List<CountQuota> countQuotaList = countQuotaService.list(new LambdaQueryWrapper<CountQuota>()
                                                    .eq(CountQuota::getAuthorityManageId, authorityManageItem.getId())
                                                    .eq(CountQuota::getCreditWay, CountQuota.CreditWay.share));
                                            for (CountQuota countQuotaItem:countQuotaList){
                                                countQuotaItem.setBalance(surplusAmount);
                                                countQuotaService.updateById(countQuotaItem);
                                            }
                                        }else if(authorityManageItem.getCreditWay().name().equals("independent")){//组员独立授信领用金额
                                            //额度评估周期
                                            if(authorityManageItem.getLineEvaluatePeriod().name().equals("day")){//每天
                                                // 如果授信类型是金额
                                                if(currentAmount.compareTo(countQuota.getBalance()) == 1){
                                                    return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每天领取的最大金额");
                                                }
                                                countQuota.setBalance(surplusAmount);
                                                countQuotaService.updateById(countQuota);
                                                //异步统计
                                                addReceiveRecord(authorityManageItem.getId(),authorityManageItem.getLineEvaluatePeriod().name(),item.getSkuCode()
                                                        ,productDetail.getMarketPrice(),item.getQuantity(),JwtUtils.getLoginUserId()
                                                        ,authorityManageItem.getCreditWay().name(),usableAmount,currentAmount);
                                            }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("week")){//每周
                                                // 如果授信类型是金额
                                                if(currentAmount.compareTo(countQuota.getBalance()) == 1){
                                                    return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每周领取的最大金额");
                                                }
                                                countQuota.setBalance(surplusAmount);
                                                countQuotaService.updateById(countQuota);
                                                //异步统计
                                                addReceiveRecord(authorityManageItem.getId(),authorityManageItem.getLineEvaluatePeriod().name(),item.getSkuCode()
                                                        ,productDetail.getMarketPrice(),item.getQuantity(),JwtUtils.getLoginUserId()
                                                        ,authorityManageItem.getCreditWay().name(),usableAmount,currentAmount);
                                            }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("month")){//每月
                                                // 如果授信类型是金额
                                                if(currentAmount.compareTo(countQuota.getBalance()) == 1){
                                                    return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每月领取的最大金额");
                                                }
                                                countQuota.setBalance(surplusAmount);
                                                countQuotaService.updateById(countQuota);
                                                //异步统计
                                                addReceiveRecord(authorityManageItem.getId(),authorityManageItem.getLineEvaluatePeriod().name(),item.getSkuCode()
                                                        ,productDetail.getMarketPrice(),item.getQuantity(),JwtUtils.getLoginUserId()
                                                        ,authorityManageItem.getCreditWay().name(),usableAmount,currentAmount);
                                            }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("quarter")){//每季度
                                                // 如果授信类型是金额
                                                if(currentAmount.compareTo(countQuota.getBalance()) == 1){
                                                    return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每季度领取的最大金额");
                                                }
                                                countQuota.setBalance(surplusAmount);
                                                countQuotaService.updateById(countQuota);
                                                //异步统计
                                                addReceiveRecord(authorityManageItem.getId(),authorityManageItem.getLineEvaluatePeriod().name(),item.getSkuCode()
                                                        ,productDetail.getMarketPrice(),item.getQuantity(),JwtUtils.getLoginUserId()
                                                        ,authorityManageItem.getCreditWay().name(),usableAmount,currentAmount);
                                            }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("year")){//每年
                                                // 如果授信类型是金额
                                                if(currentAmount.compareTo(countQuota.getBalance()) == 1){
                                                    return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每年领取的最大金额");
                                                }
                                                countQuota.setBalance(surplusAmount);
                                                countQuotaService.updateById(countQuota);
                                                //异步统计
                                                addReceiveRecord(authorityManageItem.getId(),authorityManageItem.getLineEvaluatePeriod().name(),item.getSkuCode()
                                                        ,productDetail.getMarketPrice(),item.getQuantity(),JwtUtils.getLoginUserId()
                                                        ,authorityManageItem.getCreditWay().name(),usableAmount,currentAmount);
                                            }
                                        }else if(authorityManageItem.getCreditWay().name().equals("unlimited")||authorityManageItem.getCreditWay().name().equals("unlimitedQuantity")){ //不限制领用金额或者数量
                                            //异步统计金额
                                            addReceiveRecord(authorityManageItem.getId(),authorityManageItem.getLineEvaluatePeriod().name(),item.getSkuCode()
                                                    ,productDetail.getMarketPrice(),item.getQuantity(),JwtUtils.getLoginUserId()
                                                    ,authorityManageItem.getCreditWay().name(),usableAmount,null);
                                        }
                                        break;
                                    }else if(authorityManageItem.getCreditType().getValue() == 1){ //数量
                                        //当前领取的数量
                                        Integer currentQuantity = Math.abs(item.getQuantity())*item.getQuantityPackUnit();
                                        //剩余可领数量
                                        Integer surplusQuantity = countQuota.getResidualQuantity()-currentQuantity;
                                        //权限组的授信方式
                                        if(authorityManageItem.getCreditWay().name().equals("shareQuantity")){ //组员共享领用数量
                                            //额度评估周期
                                            if(authorityManageItem.getLineEvaluatePeriod().name().equals("day")){//每天
                                                // 如果授信类型是数量
                                                if(currentQuantity>countQuota.getResidualQuantity()){
                                                    return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每天领取的最大数量");
                                                }
                                                //异步统计
                                                addReceiveRecord(authorityManageItem.getId(),authorityManageItem.getLineEvaluatePeriod().name(),item.getSkuCode()
                                                        ,productDetail.getMarketPrice(),item.getQuantity(),JwtUtils.getLoginUserId()
                                                        ,authorityManageItem.getCreditWay().name(),usableAmount,currentAmount);
                                            }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("week")){//每周
                                                // 如果授信类型是数量
                                                if(currentQuantity>countQuota.getResidualQuantity()){
                                                    return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每周领取的最大数量");
                                                }
                                                //异步统计
                                                addReceiveRecord(authorityManageItem.getId(),authorityManageItem.getLineEvaluatePeriod().name(),item.getSkuCode()
                                                        ,productDetail.getMarketPrice(),item.getQuantity(),JwtUtils.getLoginUserId()
                                                        ,authorityManageItem.getCreditWay().name(),usableAmount,currentAmount);
                                            }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("month")){//每月
                                                // 如果授信类型是数量
                                                if(currentQuantity>countQuota.getResidualQuantity()){
                                                    return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每月领取的最大数量");
                                                }
                                                //异步统计
                                                addReceiveRecord(authorityManageItem.getId(),authorityManageItem.getLineEvaluatePeriod().name(),item.getSkuCode()
                                                        ,productDetail.getMarketPrice(),item.getQuantity(),JwtUtils.getLoginUserId()
                                                        ,authorityManageItem.getCreditWay().name(),usableAmount,currentAmount);
                                            }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("quarter")){//每季度
                                                // 如果授信类型是数量
                                                if(currentQuantity>countQuota.getResidualQuantity()){
                                                    return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每季度领取的最大数量");
                                                }
                                                //异步统计
                                                addReceiveRecord(authorityManageItem.getId(),authorityManageItem.getLineEvaluatePeriod().name(),item.getSkuCode()
                                                        ,productDetail.getMarketPrice(),item.getQuantity(),JwtUtils.getLoginUserId()
                                                        ,authorityManageItem.getCreditWay().name(),usableAmount,currentAmount);
                                            }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("year")){//每年
                                                // 如果授信类型是数量
                                                if(currentQuantity>countQuota.getResidualQuantity()){
                                                    return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每年领取的最大数量");
                                                }
                                                //异步统计
                                                addReceiveRecord(authorityManageItem.getId(),authorityManageItem.getLineEvaluatePeriod().name(),item.getSkuCode()
                                                        ,productDetail.getMarketPrice(),item.getQuantity(),JwtUtils.getLoginUserId()
                                                        ,authorityManageItem.getCreditWay().name(),usableAmount,currentAmount);
                                            }
                                            List<CountQuota> countQuotaList = countQuotaService.list(new LambdaQueryWrapper<CountQuota>()
                                                    .eq(CountQuota::getAuthorityManageId, authorityManageItem.getId())
                                                    .eq(CountQuota::getCreditWay, CountQuota.CreditWay.shareQuantity));
                                            if(CollectionUtil.isNotEmpty(countQuotaList)){
                                                for (CountQuota countQuotaItem:countQuotaList){
                                                    countQuotaItem.setResidualQuantity(surplusQuantity);
                                                    countQuotaService.updateById(countQuotaItem);
                                                }
                                            }
                                        }else if(authorityManageItem.getCreditWay().name().equals("independentQuantity")){//组员独立授信领用数量
                                            //额度评估周期
                                            if(authorityManageItem.getLineEvaluatePeriod().name().equals("day")){//每天
                                                // 如果授信类型是数量
                                                if(currentQuantity>countQuota.getResidualQuantity()){
                                                    return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每天领取的最大数量");
                                                }
                                                countQuota.setResidualQuantity(surplusQuantity);
                                                countQuotaService.updateById(countQuota);
                                                //异步统计
                                                addReceiveRecord(authorityManageItem.getId(),authorityManageItem.getLineEvaluatePeriod().name(),item.getSkuCode()
                                                        ,productDetail.getMarketPrice(),item.getQuantity(),JwtUtils.getLoginUserId()
                                                        ,authorityManageItem.getCreditWay().name(),usableAmount,currentAmount);
                                            }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("week")){//每周
                                                // 如果授信类型是数量
                                                if(currentQuantity>countQuota.getResidualQuantity()){
                                                    return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每周领取的最大数量");
                                                }
                                                countQuota.setResidualQuantity(surplusQuantity);
                                                countQuotaService.updateById(countQuota);
                                                //异步统计
                                                addReceiveRecord(authorityManageItem.getId(),authorityManageItem.getLineEvaluatePeriod().name(),item.getSkuCode()
                                                        ,productDetail.getMarketPrice(),item.getQuantity(),JwtUtils.getLoginUserId()
                                                        ,authorityManageItem.getCreditWay().name(),usableAmount,currentAmount);
                                            }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("month")){//每月
                                                // 如果授信类型是数量
                                                if(currentQuantity>countQuota.getResidualQuantity()){
                                                    return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每月领取的最大数量");
                                                }
                                                countQuota.setResidualQuantity(surplusQuantity);
                                                countQuotaService.updateById(countQuota);
                                                //异步统计
                                                addReceiveRecord(authorityManageItem.getId(),authorityManageItem.getLineEvaluatePeriod().name(),item.getSkuCode()
                                                        ,productDetail.getMarketPrice(),item.getQuantity(),JwtUtils.getLoginUserId()
                                                        ,authorityManageItem.getCreditWay().name(),usableAmount,currentAmount);
                                            }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("quarter")){//每季度
                                                // 如果授信类型是数量
                                                if(currentQuantity>countQuota.getResidualQuantity()){
                                                    return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每季度领取的最大数量");
                                                }
                                                countQuota.setResidualQuantity(surplusQuantity);
                                                countQuotaService.updateById(countQuota);
                                                //异步统计
                                                addReceiveRecord(authorityManageItem.getId(),authorityManageItem.getLineEvaluatePeriod().name(),item.getSkuCode()
                                                        ,productDetail.getMarketPrice(),item.getQuantity(),JwtUtils.getLoginUserId()
                                                        ,authorityManageItem.getCreditWay().name(),usableAmount,currentAmount);
                                            }else if(authorityManageItem.getLineEvaluatePeriod().name().equals("year")){//每年
                                                // 如果授信类型是数量
                                                if(currentQuantity>countQuota.getResidualQuantity()){
                                                    return JsonResult.fail(Result.Code.OUT_OF_RANGE_ERROR.getCode(),"已超出每年领取的最大数量");
                                                }
                                                countQuota.setResidualQuantity(surplusQuantity);
                                                countQuotaService.updateById(countQuota);
                                                //异步统计
                                                addReceiveRecord(authorityManageItem.getId(),authorityManageItem.getLineEvaluatePeriod().name(),item.getSkuCode()
                                                        ,productDetail.getMarketPrice(),item.getQuantity(),JwtUtils.getLoginUserId()
                                                        ,authorityManageItem.getCreditWay().name(),usableAmount,currentAmount);
                                            }
                                        }else if(authorityManageItem.getCreditWay().name().equals("unlimited")||authorityManageItem.getCreditWay().name().equals("unlimitedQuantity")){ //不限制领用金额
                                            //异步统计金额
                                            addReceiveRecord(authorityManageItem.getId(),authorityManageItem.getLineEvaluatePeriod().name(),item.getSkuCode()
                                                    ,productDetail.getMarketPrice(),item.getQuantity(),JwtUtils.getLoginUserId()
                                                    ,authorityManageItem.getCreditWay().name(),usableAmount,null);
                                        }
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
//                if(!isExist){
//                    throw new BusinessException("该领取人没有权限！！！");
//                }
                *//*if(!isDisabled){
                    return JsonResult.fail("该权限组已被禁用了！！！");
                }*//*
            }else {
                //柜子上没有权限组 随便领
                return JsonResult.success();
            }
        }
        return JsonResult.success();
    }*/


    /**
     * 异步统计
     * @param authorityManageId 权限id
     * @param lineEvaluatePeriod 额度评估周期
     * @param skuCode 产品编码
     * @param marketPrice 价格
     * @param quantity 数量
     * @param userId 用户id
     * @param creditWay 授信方式
     * @param usableAmount  授信额度
     * @param currentAmount 当前领取的金额
     * @param creditType 授信类型
     */
    void asyncStatistical(Long authorityManageId,String lineEvaluatePeriod,String skuCode,BigDecimal marketPrice,Integer quantity
            ,Long userId,String creditWay,BigDecimal usableAmount,BigDecimal currentAmount,String creditType){
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
            @Override
            public void afterCommit() {
                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        try{
                            addReceiveRecord(authorityManageId,lineEvaluatePeriod,skuCode,marketPrice,quantity,userId,creditWay,usableAmount,currentAmount);
                        }catch (Exception e){
                            log.error("asyncStatistical fail",e);
                        }

                    }
                });
            }
        });
    }

    void addReceiveRecord(Long authorityManageId,String lineEvaluatePeriod,String skuCode,BigDecimal marketPrice
            ,Integer quantity,Long userId,String creditWay,BigDecimal usableAmount,BigDecimal currentAmount){
        ReceiveRecord receiveRecord = new ReceiveRecord();
        if(null != userId) {
            JsonResult<UserVO> userInfo = userClient.getUserInfo(userId);
            receiveRecord.setReceiverName(userInfo.getData().getUsername());
        }
        receiveRecord.setSkuCode(skuCode);
        receiveRecord.setReceiverId(userId);
        receiveRecord.setReceiverMoney(marketPrice.multiply(BigDecimal.valueOf(quantity)));
        receiveRecord.setReceiverTime(dateLocalDateTime(new Date()));
        receiveRecord.setQuantity(quantity);
        receiveRecord.setAuthorityManageId(authorityManageId);
        if(StringUtils.isNotBlank(lineEvaluatePeriod)){
            if(lineEvaluatePeriod.equals("day")){//每天
                receiveRecord.setLineEvaluatePeriod(ReceiveRecord.LineEvaluatePeriod.day);
            }else if(lineEvaluatePeriod.equals("week")) {//每周
                receiveRecord.setLineEvaluatePeriod(ReceiveRecord.LineEvaluatePeriod.week);
            }else if(lineEvaluatePeriod.equals("month")){//每月
                receiveRecord.setLineEvaluatePeriod(ReceiveRecord.LineEvaluatePeriod.month);
            }else if(lineEvaluatePeriod.equals("quarter")){//每季度
                receiveRecord.setLineEvaluatePeriod(ReceiveRecord.LineEvaluatePeriod.quarter);
            }else if(lineEvaluatePeriod.equals("year")){//每年
                receiveRecord.setLineEvaluatePeriod(ReceiveRecord.LineEvaluatePeriod.year);
            }
        }
        receiveRecordService.save(receiveRecord);
    }

//    void addReceiveRecord(Long authorityManageId,String lineEvaluatePeriod,String skuCode,BigDecimal marketPrice
//            ,Integer quantity,Long userId,String creditWay,BigDecimal usableAmount,BigDecimal currentAmount){
//        JsonResult<UserVO> userInfo = userClient.getUserInfo(userId);
//        if(creditWay.equals("share")){//组员共享领用金额
//            if(lineEvaluatePeriod.equals("day")){//每天
//                ReceiveRecord receiveRecord = new ReceiveRecord();
//                String todayTime = DateTimeFormatter.ofPattern("yyyy-MM-dd").format(LocalDateTime.now());
//                //当天领取的总金额
//                Double totalMoney = receiveRecordService.sumByTotalMoney(authorityManageId,todayTime);
////                //当天领取的总数量
////                Integer totalQuantity = receiveRecordService.sumByTotalQuantity(authorityManageId,todayTime);
//                if(totalMoney!=null){
//                    //剩余金额
//                    BigDecimal surplusAmount = usableAmount.subtract(BigDecimal.valueOf(totalMoney).add(currentAmount));
//                    receiveRecord.setBalance(surplusAmount);
//                }else{
//                    receiveRecord.setBalance(usableAmount.subtract(marketPrice.multiply(BigDecimal.valueOf(quantity))));
//                }
//                receiveRecord.setSkuCode(skuCode);
//                receiveRecord.setReceiverId(userId);
//                receiveRecord.setReceiverName(userInfo.getData().getUsername());
//                receiveRecord.setReceiverMoney(marketPrice.multiply(BigDecimal.valueOf(quantity)));
//                receiveRecord.setReceiverTime(dateLocalDateTime(new Date()));
//                receiveRecord.setQuantity(quantity);
//                receiveRecord.setAuthorityManageId(authorityManageId);
//                receiveRecord.setLineEvaluatePeriod(ReceiveRecord.LineEvaluatePeriod.day);
//                receiveRecordService.save(receiveRecord);
//            }else if(lineEvaluatePeriod.equals("week")){//每周
//                ReceiveRecord receiveRecord = new ReceiveRecord();
//                Double sumMoney = receiveRecordService.sumMoney(authorityManageId,FindDateStatusUtil.getWeekStart(new Date()), FindDateStatusUtil.getWeekEndTime());
//                if(sumMoney!=null){
//                    //剩余金额
//                    BigDecimal surplusAmount = usableAmount.subtract(BigDecimal.valueOf(sumMoney).add(currentAmount));
//                    receiveRecord.setBalance(surplusAmount);
//                }else{
//                    receiveRecord.setBalance(usableAmount.subtract(marketPrice.multiply(BigDecimal.valueOf(quantity))));
//                }
//                receiveRecord.setSkuCode(skuCode);
//                receiveRecord.setReceiverId(userId);
//                receiveRecord.setReceiverName(userInfo.getData().getUsername());
//                receiveRecord.setReceiverMoney(marketPrice.multiply(BigDecimal.valueOf(quantity)));
//                receiveRecord.setReceiverTime(dateLocalDateTime(new Date()));
//                receiveRecord.setQuantity(quantity);
//                receiveRecord.setAuthorityManageId(authorityManageId);
//                receiveRecord.setLineEvaluatePeriod(ReceiveRecord.LineEvaluatePeriod.week);
//                receiveRecordService.save(receiveRecord);
//            }else if(lineEvaluatePeriod.equals("month")){//每月
//                ReceiveRecord receiveRecord = new ReceiveRecord();
//                Double sumMoney = receiveRecordService.sumMoney(authorityManageId,FindDateStatusUtil.getMonthStartTime(), FindDateStatusUtil.getMonthEndTime());
//                if(sumMoney!=null){
//                    //剩余金额
//                    BigDecimal surplusAmount = usableAmount.subtract(BigDecimal.valueOf(sumMoney).add(currentAmount));
//                    receiveRecord.setBalance(surplusAmount);
//                }else{
//                    receiveRecord.setBalance(usableAmount.subtract(marketPrice.multiply(BigDecimal.valueOf(quantity))));
//                }
//                receiveRecord.setSkuCode(skuCode);
//                receiveRecord.setReceiverId(userId);
//                receiveRecord.setReceiverName(userInfo.getData().getUsername());
//                receiveRecord.setReceiverMoney(marketPrice.multiply(BigDecimal.valueOf(quantity)));
//                receiveRecord.setReceiverTime(dateLocalDateTime(new Date()));
//                receiveRecord.setQuantity(quantity);
//                receiveRecord.setAuthorityManageId(authorityManageId);
//                receiveRecord.setLineEvaluatePeriod(ReceiveRecord.LineEvaluatePeriod.month);
//                receiveRecordService.save(receiveRecord);
//            }else if(lineEvaluatePeriod.equals("quarter")){//每季度
//                ReceiveRecord receiveRecord = new ReceiveRecord();
//                Double sumMoney = receiveRecordService.sumMoney(authorityManageId,FindDateStatusUtil.getQuarterStartTime(new Date()), FindDateStatusUtil.getQuarterEndTime(new Date()));
//                if(sumMoney!=null){
//                    //剩余金额
//                    BigDecimal surplusAmount = usableAmount.subtract(BigDecimal.valueOf(sumMoney).add(currentAmount));
//                    receiveRecord.setBalance(surplusAmount);
//                }
//                receiveRecord.setSkuCode(skuCode);
//                receiveRecord.setReceiverId(userId);
//                receiveRecord.setReceiverName(userInfo.getData().getUsername());
//                receiveRecord.setReceiverMoney(marketPrice.multiply(BigDecimal.valueOf(quantity)));
//                receiveRecord.setReceiverTime(dateLocalDateTime(new Date()));
//                receiveRecord.setQuantity(quantity);
//                receiveRecord.setAuthorityManageId(authorityManageId);
//                receiveRecord.setLineEvaluatePeriod(ReceiveRecord.LineEvaluatePeriod.quarter);
//                receiveRecordService.save(receiveRecord);
//            }else if(lineEvaluatePeriod.equals("year")){//每年
//                ReceiveRecord receiveRecord = new ReceiveRecord();
//                Double sumMoney = receiveRecordService.sumMoney(authorityManageId,FindDateStatusUtil.getYearStartTime(), FindDateStatusUtil.getYearEndTime());
//                //剩余金额
//                if(sumMoney!=null){
//                    BigDecimal surplusAmount = usableAmount.subtract(BigDecimal.valueOf(sumMoney).add(currentAmount));
//                    receiveRecord.setBalance(surplusAmount);
//                }else{
//                    receiveRecord.setBalance(usableAmount.subtract(marketPrice.multiply(BigDecimal.valueOf(quantity))));
//                }
//                receiveRecord.setSkuCode(skuCode);
//                receiveRecord.setReceiverId(userId);
//                receiveRecord.setReceiverName(userInfo.getData().getUsername());
//                receiveRecord.setReceiverMoney(marketPrice.multiply(BigDecimal.valueOf(quantity)));
//                receiveRecord.setReceiverTime(dateLocalDateTime(new Date()));
//                receiveRecord.setQuantity(quantity);
//                receiveRecord.setAuthorityManageId(authorityManageId);
//                receiveRecord.setLineEvaluatePeriod(ReceiveRecord.LineEvaluatePeriod.year);
//                receiveRecordService.save(receiveRecord);
//            }
//        }else if(creditWay.equals("independent")){//组员独立授信领用金额
//            if(lineEvaluatePeriod.equals("day")){//每天
//                ReceiveRecord receiveRecord = new ReceiveRecord();
//                String todayTime = DateTimeFormatter.ofPattern("yyyy-MM-dd").format(LocalDateTime.now());
//                //当天领取的总金额
//                Double totalMoney = receiveRecordService.sumIndependentByTotalMoney(authorityManageId,userId,todayTime);
//                if(totalMoney!=null){
//                    //剩余金额
//                    BigDecimal surplusAmount = usableAmount.subtract(BigDecimal.valueOf(totalMoney).add(currentAmount));
//                    receiveRecord.setBalance(surplusAmount);
//                }else{
//                    receiveRecord.setBalance(usableAmount.subtract(marketPrice.multiply(BigDecimal.valueOf(quantity))));
//                }
//                receiveRecord.setSkuCode(skuCode);
//                receiveRecord.setReceiverId(userId);
//                receiveRecord.setReceiverName(userInfo.getData().getUsername());
//                receiveRecord.setReceiverMoney(marketPrice.multiply(BigDecimal.valueOf(quantity)));
//                receiveRecord.setReceiverTime(dateLocalDateTime(new Date()));
//                receiveRecord.setQuantity(quantity);
//                receiveRecord.setAuthorityManageId(authorityManageId);
//                receiveRecord.setLineEvaluatePeriod(ReceiveRecord.LineEvaluatePeriod.day);
//                receiveRecordService.save(receiveRecord);
//            }else if(lineEvaluatePeriod.equals("week")){//每周
//                ReceiveRecord receiveRecord = new ReceiveRecord();
//                Map<String, Object> params = new HashMap<>();
//                params.put("receiverId",userId);
//                params.put("authorityManageId",authorityManageId);
//                params.put("startTime",FindDateStatusUtil.getWeekStart(new Date()));
//                params.put("endTime",FindDateStatusUtil.getWeekEndTime());
//                Double sumMoney = receiveRecordService.sumIndependentMoneyByReceiverId(params);
//                if(sumMoney!=null){
//                    //剩余金额
//                    BigDecimal surplusAmount = usableAmount.subtract(BigDecimal.valueOf(sumMoney).add(currentAmount));
//                    receiveRecord.setBalance(surplusAmount);
//                }else{
//                    receiveRecord.setBalance(usableAmount.subtract(marketPrice.multiply(BigDecimal.valueOf(quantity))));
//                }
//                receiveRecord.setSkuCode(skuCode);
//                receiveRecord.setReceiverId(userId);
//                receiveRecord.setReceiverName(userInfo.getData().getUsername());
//                receiveRecord.setReceiverMoney(marketPrice.multiply(BigDecimal.valueOf(quantity)));
//                receiveRecord.setReceiverTime(dateLocalDateTime(new Date()));
//                receiveRecord.setQuantity(quantity);
//                receiveRecord.setAuthorityManageId(authorityManageId);
//                receiveRecord.setLineEvaluatePeriod(ReceiveRecord.LineEvaluatePeriod.week);
//                receiveRecordService.save(receiveRecord);
//            }else if(lineEvaluatePeriod.equals("month")){//每月
//                ReceiveRecord receiveRecord = new ReceiveRecord();
//                Map<String, Object> params = new HashMap<>();
//                params.put("receiverId",userId);
//                params.put("authorityManageId",authorityManageId);
//                params.put("startTime",FindDateStatusUtil.getMonthStartTime());
//                params.put("endTime",FindDateStatusUtil.getMonthEndTime());
//                Double sumMoney = receiveRecordService.sumIndependentMoneyByReceiverId(params);
//                if(sumMoney!=null){
//                    //剩余金额
//                    BigDecimal surplusAmount = usableAmount.subtract(BigDecimal.valueOf(sumMoney).add(currentAmount));
//                    receiveRecord.setBalance(surplusAmount);
//                }else{
//                    receiveRecord.setBalance(usableAmount.subtract(marketPrice.multiply(BigDecimal.valueOf(quantity))));
//                }
//                receiveRecord.setSkuCode(skuCode);
//                receiveRecord.setReceiverId(userId);
//                receiveRecord.setReceiverName(userInfo.getData().getUsername());
//                receiveRecord.setReceiverMoney(marketPrice.multiply(BigDecimal.valueOf(quantity)));
//                receiveRecord.setReceiverTime(dateLocalDateTime(new Date()));
//                receiveRecord.setQuantity(quantity);
//                receiveRecord.setAuthorityManageId(authorityManageId);
//                receiveRecord.setLineEvaluatePeriod(ReceiveRecord.LineEvaluatePeriod.month);
//                receiveRecordService.save(receiveRecord);
//            }else if(lineEvaluatePeriod.equals("quarter")){//每季度
//                ReceiveRecord receiveRecord = new ReceiveRecord();
//                Map<String, Object> params = new HashMap<>();
//                params.put("receiverId",userId);
//                params.put("authorityManageId",authorityManageId);
//                params.put("startTime",FindDateStatusUtil.getQuarterStartTime(new Date()));
//                params.put("endTime",FindDateStatusUtil.getQuarterEndTime(new Date()));
//                Double sumMoney = receiveRecordService.sumIndependentMoneyByReceiverId(params);
//                if(sumMoney!=null){
//                    //剩余金额
//                    BigDecimal surplusAmount = usableAmount.subtract(BigDecimal.valueOf(sumMoney).add(currentAmount));
//                    receiveRecord.setBalance(surplusAmount);
//                }else{
//                    receiveRecord.setBalance(usableAmount.subtract(marketPrice.multiply(BigDecimal.valueOf(quantity))));
//                }
//                receiveRecord.setSkuCode(skuCode);
//                receiveRecord.setReceiverId(userId);
//                receiveRecord.setReceiverName(userInfo.getData().getUsername());
//                receiveRecord.setReceiverMoney(marketPrice.multiply(BigDecimal.valueOf(quantity)));
//                receiveRecord.setReceiverTime(dateLocalDateTime(new Date()));
//                receiveRecord.setQuantity(quantity);
//                receiveRecord.setAuthorityManageId(authorityManageId);
//                receiveRecord.setLineEvaluatePeriod(ReceiveRecord.LineEvaluatePeriod.quarter);
//                receiveRecordService.save(receiveRecord);
//            }else if(lineEvaluatePeriod.equals("year")){//每年
//                ReceiveRecord receiveRecord = new ReceiveRecord();
//                Map<String, Object> params = new HashMap<>();
//                params.put("receiverId",userId);
//                params.put("authorityManageId",authorityManageId);
//                params.put("startTime",FindDateStatusUtil.getYearStartTime());
//                params.put("endTime",FindDateStatusUtil.getYearEndTime());
//                Double sumMoney = receiveRecordService.sumIndependentMoneyByReceiverId(params);
//                if(sumMoney!=null){
//                    //剩余金额
//                    BigDecimal surplusAmount = usableAmount.subtract(BigDecimal.valueOf(sumMoney).add(currentAmount));
//                    receiveRecord.setBalance(surplusAmount);
//                }else{
//                    receiveRecord.setBalance(usableAmount.subtract(marketPrice.multiply(BigDecimal.valueOf(quantity))));
//                }
//                receiveRecord.setSkuCode(skuCode);
//                receiveRecord.setReceiverId(userId);
//                receiveRecord.setReceiverName(userInfo.getData().getUsername());
//                receiveRecord.setReceiverMoney(marketPrice.multiply(BigDecimal.valueOf(quantity)));
//                receiveRecord.setReceiverTime(dateLocalDateTime(new Date()));
//                receiveRecord.setQuantity(quantity);
//                receiveRecord.setAuthorityManageId(authorityManageId);
//                receiveRecord.setLineEvaluatePeriod(ReceiveRecord.LineEvaluatePeriod.year);
//                receiveRecordService.save(receiveRecord);
//            }
//        }else if(creditWay.equals("unlimited")){//不限制领用金额
//            ReceiveRecord receiveRecord = new ReceiveRecord();
//            receiveRecord.setSkuCode(skuCode);
//            receiveRecord.setReceiverId(userId);
//            receiveRecord.setReceiverName(userInfo.getData().getUsername());
//            receiveRecord.setReceiverMoney(marketPrice.multiply(BigDecimal.valueOf(quantity)));
//            receiveRecord.setReceiverTime(dateLocalDateTime(new Date()));
//            receiveRecord.setQuantity(quantity);
//            receiveRecord.setAuthorityManageId(authorityManageId);
//            receiveRecordService.save(receiveRecord);
//        }
//    }

    private LocalDateTime dateLocalDateTime(Date date) {
        if (date == null) {
            return null;
        }
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
    }
}
